mrd*_*mrd -1 objective-c nsdate nsdatecomponents ios
我有个约会.
NSLog 显示为:
2014-05-11 21:59:59 +0000
Run Code Online (Sandbox Code Playgroud)
现在我想获得相同的日期,但小时,分钟和秒设置为零:
2014-05-11 00:00:00 +0000
Run Code Online (Sandbox Code Playgroud)
我的代码:
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone localTimeZone]];
NSDateComponents *components = [calendar components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:dayOfWeek];
NSLog(@"components: %@", components);
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:[components year]];
[comps setMonth:[components month]];
[comps setDay:[components day]];
[comps setHour:0];
[comps setMinute:0];
[comps setSecond:0];
NSLog(@"New date: %@", [calendar dateFromComponents:comps]);
Run Code Online (Sandbox Code Playgroud)
但NSLog显示:
2014-05-10 22:00:00 +0000
Run Code Online (Sandbox Code Playgroud)
似乎日和小时计算错误.请注意,我在德国,但我使用,[NSTimeZone localTimeZone]因为我认为这应该返回正确的时区?
真的没有问题...仍然:
NSDate始终为UTC.当您致电NSLog时,它会显示在夏令时关闭的情况下在伦敦的时间.因此,您的初始NSDate在伦敦晚上10点之前是一秒钟,夏令时关闭(UTC),午夜前一秒钟.然后,您计算一个刚刚在德国开始的NSDate.在那个时间点,它是在UTC的前一天晚上10点,这就是NSLog显示的内容.
| 归档时间: |
|
| 查看次数: |
1101 次 |
| 最近记录: |