Question

My code is like below

NSDateComponents *components = [[NSDateComponents alloc] init];
components.year = [aDay.year intValue];   // 2012
components.month = [aDay.month intValue]; // 2
components.day = [aDay.day intValue];  // 1
components.hour = components.minute = components.second = 0;
NSDate *now = [self.calender dateFromComponents:components];

and about self.calendar, I tried both the 2 methods:

self.calendar = [NSCalendar currentCalendar];
self.calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

but after this, when I print the date "now", it is always this:

(gdb) po now
2012-01-31 16:00:00 +0000

The date "now" is supposed to be 2012-02-01 00:00:00

Apparently there is 8 hours difference, and I'm now in China so I am in a +0800 timezone I guess?

How could I fix this problem? Do I have to deal with the timeZone?

Thanks a lot!

Était-ce utile?

La solution

Well, why don't you try setting the timezone to one of your liking:

NSTimeZone *zone = [NSTimeZone timeZoneWithName:@"PST"];
[calendar setTimeZone:zone];

You can see a list of the known time zones with:

NSArray *timezones = [NSTimeZone knownTimeZoneNames];
NSLog(@"%@", timezones);

Autres conseils

I've figured this out.

What it displays is correct since the NSDate conserves the absolute time, so the time zone is always +0000,

and it is better to keep it this way since I need compare: method in NSDate,etc

the only difference is when you are going to translate the absolute date to local date readable string for users, just take care of it.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top