1

我正在解析一个日期,并希望将其转换为用户当前所在的时区。此外,我想显示一个倒计时,显示距离特定日期还有多少天。这是我的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *MyIdentifier = @"MyIdentifier";
    MyIdentifier = @"tblCellView";

    TableCellView *cell = (TableCellView *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if(cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"TableCellView" owner:self options:nil];
        cell = tblCell;
    }

    NSString *cellstring = [NSString stringWithFormat:@"%@", [[self.parseResults objectAtIndex:indexPath.row] objectForKey:@"title"]];
    NSString *cellnumber = [NSString stringWithFormat:@"%@", [[self.parseResults objectAtIndex:indexPath.row] objectForKey:@"number"]];

    NSString *epinumber = [cellnumber stringByReplacingOccurrencesOfString:@"-" withString:@""];

    NSString *celldescription = [NSString stringWithFormat:@"%@",[[self.parseResults objectAtIndex:indexPath.row] objectForKey:@"date"]];

    //NSLog(@"%@", celldescription);
    //celldescription returns a value


    NSString *finalString = [celldescription stringByReplacingOccurrencesOfString:@"EST" withString:@""];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]];

    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"EST"]];
    // this is imporant - we set our input date format to match our input string
    // if format doesn't match you'll get nil from your string, so be careful
    [dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss"];
    NSDate *dateFromString = [[NSDate alloc] init];
    // voila!
    dateFromString = [dateFormatter dateFromString:finalString];

    NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];

    [dateFormatter1 setDateFormat:@"EEE, dd MMM yyyy HH:mm aaa"];

    NSString *dateDisplay = [dateFormatter1 stringFromDate:dateFromString];

    [dateFormatter release];

    NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]autorelease];

    int units = NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

    NSDateComponents *components = [calendar components:units fromDate:[NSDate date] toDate:dateFromString options:0];
    NSString *string = [NSString stringWithFormat:@"%d", [components day]];

    if (indexPath.row == 0) {
        cell.cellText.textColor = [UIColor redColor];
    } else {
        cell.cellText.textColor = [UIColor blackColor];
    }

    [cell setLabelText:cellstring];
    [cell setDateText:dateDisplay];
    [cell setCountText:string];
    [cell setNumberText:epinumber];


    return cell;
}

但我总是收到以下错误:

2012-12-29 13:10:23.139 spncountdown[87678:c07] *** -[__NSCFCalendar components:fromDate:toDate:options:]: toDate cannot be nil
I mean really, what do you think that operation is supposed to mean with a nil toDate?
An exception has been avoided for now.
A few of these errors are going to be reported with this complaint, then further violations will simply silently do whatever random thing results from the nil.
Here is the backtrace where this occurred this time (some frames may be missing due to compiler optimizations):
(
    0   CoreFoundation                      0x012c1c78 -[__NSCFCalendar components:fromDate:toDate:options:] + 200
    1   spncountdown                        0x000340bf -[SixthViewController convertWork] + 831
    2   spncountdown                        0x00033c14 -[SixthViewController tableView:cellForRowAtIndexPath:] + 820
    3   UIKit                               0x020988fb -[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:withIndexPath:] + 412
    4   UIKit                               0x020989cf -[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:] + 69
    5   UIKit                               0x020811bb -[UITableView(_UITableViewPrivate) _updateVisibleCellsNow:] + 1863
    6   UIKit                               0x02091b4b -[UITableView layoutSubviews] + 241
    7   UIKit                               0x0202e2dd -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 279
    8   libobjc.A.dylib                     0x030ad6b0 -[NSObject performSelector:withObject:] + 70
    9   QuartzCore                          0x01dcdfc0 -[CALayer layoutSublayers] + 240
    10  QuartzCore                          0x01dc233c _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 468
    11  QuartzCore                          0x01dc2150 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 26
    12  QuartzCore                          0x01d400bc _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 324
    13  QuartzCore                          0x01d41227 _ZN2CA11Transaction6commitEv + 395
    14  QuartzCore                          0x01de3b50 +[CATransaction flush] + 52
    15  UIKit                               0x01ff3edf _afterCACommitHandler + 132
    16  CoreFoundation                      0x0127aafe __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 30
    17  CoreFoundation                      0x0127aa3d __CFRunLoopDoObservers + 381
    18  CoreFoundation                      0x012587c2 __CFRunLoopRun + 1106
    19  CoreFoundation                      0x01257f44 CFRunLoopRunSpecific + 276
    20  CoreFoundation                      0x01257e1b CFRunLoopRunInMode + 123
    21  GraphicsServices                    0x03b127e3 GSEventRunModal + 88
    22  GraphicsServices                    0x03b12668 GSEventRun + 104
    23  UIKit                               0x01fddffc UIApplicationMain + 1211
    24  spncountdown                        0x00003222 main + 130
    25  spncountdown                        0x00003155 start + 53
)
4

4 回答 4

2

很明显,您的dateFromStringis nil,这可能是因为日期格式问题。尝试打印出格式化的字符串并理解为什么NSDateFormatter没有正确解析它。

于 2012-12-29T12:31:49.790 回答
0

I fixed this issue for me. I hope this can help to anyone. My problem was with the code which is commented. I solved the problem with new written code which are below this commented code. Code is given as:

//    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    //    df.dateStyle = NSDateFormatterMediumStyle;
    //
    //    NSCalendar *calendar = [NSCalendar currentCalendar];
    //    int year   =    [[calendar components:NSYearCalendarUnit  fromDate:[datePickerView date]] year];
    //    int month  =    [[calendar components:NSMonthCalendarUnit fromDate:[datePickerView date]] month];
    //    int day    =    [[calendar components:NSDayCalendarUnit   fromDate:[datePickerView date]] day];
    //    

    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[datePickerView date]];
    NSInteger day = [components day];
    NSInteger month = [components month];
    NSInteger year = [components year];

    date = [NSString stringWithFormat:@"%d-%d-%d",year,month, day];
    NSLog(@"Updated Date: %@",date);
于 2013-07-18T13:32:27.017 回答
0

作为您的NSLog打印件:Wed, 27 Feb 2013 21:00:00

使用此代码:

NSString *finalString=@"Wed, 27 Feb 2013 21:00:00";
NSDateFormatter *dateFormatter2=[NSDateFormatter new];
[dateFormatter2 setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss"];

NSLog(@"finalString: %@",[dateFormatter2 dateFromString:finalString]);

NSDate *dateFromString =[dateFormatter2 dateFromString:finalString];

[dateFormatter2 setDateFormat:@"dd MMM YYYY"];
NSLog(@"dateFromString  : %@",[dateFormatter2 stringFromDate:dateFromString]);

输出:

finalString: 2013-02-27 15:30:00 +0000
dateFromString  : 27 Feb 2013
于 2012-12-29T12:31:43.223 回答
0

我解决了我的问题。在下面的示例中,我为“日期”传递了“零”。

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components:NSWeekdayCalendarUnit fromDate:date];
于 2015-06-24T10:43:43.490 回答