0

myObject.theEnd并且myObject.theStart是字符串,它具有Thu Feb 31类似的日期格式......

NSDateFormatter *format=[[NSDateFormatter alloc] init];
        [format setDateFormat:@"EEE MMM dd"]; 
        NSDate *end = [format dateFromString:myObject.theEnd];
        NSDate *start = [format dateFromString:myObject.theStart];
        NSDate *current = [NSDate date];

theEnd什么时候Thu Feb 31NSDate *end显示为1970-5-19 14:30 +0000。与NSDate *start和相同NSDate *current

为什么是这样 ?我该如何解决这个问题?

4

1 回答 1

6

我敢打赌theEnd没有显示为1970-05-19 14:30 +0000. 我敢打赌它的显示是(null)因为从来没有 2 月 31 日!例如我得到:

NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"EEE MMM dd"]; 
NSDate *end = [format dateFromString:@"Thu Feb 31"];
NSLog(@"end = %@", end);

=>

2012-05-20 16:38:31.620 test-date[42307:707] end = (null)

另外我敢打赌,您所在的时区是 UTC 以东 9.5 小时。实际上,1970-05-19 14:30 +0000当您解析Sun May 20. 例如,我目前在 BST,所以 UTC+0100 我得到:

NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"EEE MMM dd"]; 
NSDate *start = [format dateFromString:@"Sun May 20"];
NSLog(@"start = %@", start);

=>

2012-05-20 16:38:31.621 test-date[42307:707] start = 1970-05-19 23:00:00 +0000

由于它在当前时区(UTC格式)中解析为1970-05-20 00:00:00(没有年份,因此该组件为 " 0" = )。19701970-05-19 23:00:00 +0000

如果您想解决该问题,请将格式化程序的时区设置为 UTC:

[format setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

要将年份变为当前年份,您可以执行以下操作:

NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"EEE MMM dd"];
[format setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

NSDate *start = [format dateFromString:@"Sun May 20"];
NSLog(@"start = %@", start);

NSDate *today = [NSDate date];

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *todayComponents = [gregorian components:NSYearCalendarUnit fromDate:today];
NSDateComponents *startComponents = [gregorian components:(NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:start];

[startComponents setYear:[todayComponents year]];
[startComponents setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

start = [gregorian dateFromComponents:startComponents];

NSLog(@"start = %@", start);

它不是那么漂亮,但它确实有效。或者,您可以将当前年份附加到您传递给格式化程序的字符串并添加yyyy到格式化程序样式中:

NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"EEE MMM dd yyyy"];
[format setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *todayComponents = [gregorian components:NSYearCalendarUnit fromDate:today];

NSString *dateString = [NSString stringWithFormat:@"Sun May 20 %i", [todayComponents year]];

NSDate *start = [format dateFromString:dateString];
NSLog(@"start = %@", start);
于 2012-05-20T15:42:45.453 回答