简体   繁体   中英

NSDate from NSDateComponent short by 1 hour?

When trying to specify a date (ie 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM