开发者

NSDate from NSDateComponent short by 1 hour?

开发者 https://www.devze.com 2023-02-22 15:09 出处:网络
When trying to specify a date (i.e. a开发者_运维百科 birthday) using NSDateComponent I realised that the date I was getting back was 1 hour short.

When trying to specify a date (i.e. a开发者_运维百科 birthday) using NSDateComponent I realised that the date I was getting back was 1 hour short.

NSDateComponents *birthdayComponents = [[NSDateComponents alloc] init];
[birthdayComponents setDay:5];
[birthdayComponents setMonth:3];
[birthdayComponents setYear:1968];

NSDate *birthday = [[NSCalendar currentCalendar] dateFromComponents:birthdayComponents];
NSLog(@"BIRTHDAY: %@", birthday);
[birthdayComponents release];

.

OUTPUT: "BIRTHDAY: 1968-03-04 23:00:00 +0000"

I can correct this by adding:

[birthdayComponents setHour:1];

but was curious why just setting 5, 3, 1968 did not give 1968-03-05 00:00:00 +0000?


You didn't set the timeZone property of birthdayComponents, so it defaults to UTC. When you create a date from it, the date components are translated to your local time zone.


What is your current timezone? ;)

Your output when you log the date is showing the time in GMT, you are probably creating it in your time zone, which is one hour off of GMT.


I ran into similar issues due to daylight savings - was getting 0400 vs 0500, etc. I resolved this by setting the timezone and locale.

// set the locale (for date calculations)
NSLocale *locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"es_US"] autorelease];
endDate.locale = locale;
0

精彩评论

暂无评论...
验证码 换一张
取 消