我有以下代码将日期时间设置为0小时,0分钟,0秒,通过使用日期中的YEAR,MONTH和DAY组件来构建一个新的:NSDate设置的时间,而不是预期的结果
NSDate *date = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:date];
NSDate *newDate = [gregorian dateFromComponents:comps];
NSLog(@"date: %@, newDate: %@", date, newDate);
输出是:
date: 2012-11-06 11:44:09 +0000, newDate: 2012-11-05 23:00:00 +0000
,但我期待新的日期为:2012-11-06 00:00:00 +0000
发生了什么事,我应该知道的?
使用上述格式化程序设置打印日期是相同的。您能否提供一些关于夏令时如何影响NSDate创建或日历的说明? – SolidSun
通过考虑设备/用户设置的时区,夏令时会影响'[NSDate date]'的结果。通过使用不同的时区,可以确定与另一个时区相关的日期。请参阅对我的回答所做的修改。 – CaptainRedmuff
@CaptainRedmuff“夏令时影响[NSDate date]的结果”:这是不正确的; 'NSDate'不受日历,时区,地区等的影响。'NSDate'代表绝对时间点。 –