NSDate奇怪的时刻

时间:2013-09-16 09:05:10

标签: ios nsdate

我有一个奇怪的小时计算。记下这个日志:

NSLog(@"Load Data in event %@ %d",currentDate,[currentDate hour]);

在日志中:

Load Data in event 2013-09-18 06:30:00 +0000 2147483647

其中currentDate是NSDate,NSDate的类别是:

- (int)hour
{
     NSCalendar *calendar = [NSCalendar currentCalendar];
     NSDateComponents *components = [calendar components:(NSHourCalendarUnit |    NSMinuteCalendarUnit) fromDate:self];
     [components setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
     NSInteger hour = [components hour];
     return hour;
}

3 个答案:

答案 0 :(得分:3)

NSDate *today = [NSDate date];

NSLog(@"Today's date: %@",today);



unsigned hourAndMinuteFlags = NSHourCalendarUnit | NSMinuteCalendarUnit;

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

[calendar setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];

NSDateComponents* travelDateTimeComponents = [calendar components:hourAndMinuteFlags fromDate:today];


NSString* hours = [NSString stringWithFormat:@"%02i", [travelDateTimeComponents hour]];

NSString* minutes = [NSString stringWithFormat:@"%02i", [travelDateTimeComponents minute]];



NSLog(@"Hours: %@",hours);

NSLog(@"Minutes: %@",minutes);

答案 1 :(得分:2)

删除

[components setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];

请注意NSDateComponents不执行任何时区计算,因此在查询值之前在其上设置时区没有意义。

答案 2 :(得分:-1)

尝试使用以下代码:

NSString *strCurrentDate;
NSString *strNewDate;
NSDate *date = [NSDate date];
NSDateFormatter *df =[[NSDateFormatter alloc]init];
[df setDateFormat:@"yyyy-MM-dd HH:mm a"];
strCurrentDate = [df stringFromDate:date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
NSDate *newDate= [calendar dateByAddingComponents:components toDate:date options:0];
[df setDateStyle:NSDateFormatterMediumStyle];
[df setTimeStyle:NSDateFormatterMediumStyle];
strNewDate = [df stringFromDate:newDate];
NSLog(@"New Date and Time: %@",strNewDate)