我有一段过去确实有用的代码(至少我认为它的确如此,否则问题早已被认出)。自从几个星期以来,可能是自DST以来,它开始产生不正确的结果。DST(神秘失踪的两小时)的时区问题
这段代码应该生成一个NSDate对象,指向给定日期周的第一天00:00h。
NSCalendar *gregorianCalender = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDate *firstDayDate;
unsigned yearAndWeek = NSTimeZoneCalendarUnit | NSYearCalendarUnit | NSWeekCalendarUnit;
// retrieve the components from the current date
NSDateComponents *compsCurrentDate = [gregorianCalender components:yearAndWeek fromDate:date];
[compsCurrentDate setWeekday:2]; // Monday
[compsCurrentDate setHour:0];
[compsCurrentDate setMinute:0];
[compsCurrentDate setSecond:0];
// make a date from the modfied components
firstDayDate = [gregorianCalender dateFromComponents:compsCurrentDate];
NSLog(@"MONDAY: %@", firstDayDate);
今天是五月的第24届所以最后一行应打印像
MONDAY: 2011-05-23 00:00:00 +0000
但它确实打印以下
MONDAY: 2011-05-22 22:00:00 +0000
这显然是错误的。五月二十二日是星期天。现在,为了让事情奇怪,当我再次改变setHour:0
到
[compsCurrentDate setHour:2];
我的猜测是,有什么东西错了时区的结果是正确的。但花了半天的时间在Apple文档上,谷歌和stackoverflow我无法弄清楚问题是什么。也许我使用了错误的关键字,或者我是唯一一个遇到这个问题的人。
每一条信息都非常感谢!请让我知道你在想什么!谢谢!