obtener un NSDate de NSCalendar y NSDateComponents

Mi código es como el siguiente

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?

¡Muchas gracias!

preguntado el 01 de febrero de 12 a las 04:02

2 Respuestas

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);

Respondido 01 Feb 12, 09:02

Thanks! So the problems is still about time zone? Is there any method to directly get the user's current time zone? just like [NSCalendar currentCalendar]? - Wang Liang

I've check the default timeZone, it's is default Asia/Hebin, so... what can I do.? - Wang Liang

He descubierto esto.

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.

Respondido 03 Feb 12, 09:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.