views:

181

answers:

2

I need to set a NSDate to a specific date, time and timezone for an iPhone App.

The example code below works fine on iOS 4 as the setTimeZone was introduced with iOS 4. How could I easily set a NSDate to a date, time and timezone without using setTimeZone so it can be used on iOS 3.0 devices?

    NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:2010];
[comps setMonth:8];
[comps setDay:24];
[comps setHour:17];
[comps setMinute:5];
[comps setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"] ];

NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *referenceTime = [cal dateFromComponents:comps];

Guess this should be simple, but somehow NSDate, components and calendars and I are not good friends...

+1  A: 

NDates have no concept of time zones in and of themselves. They're basically seconds since a certain arbitrary date at GMT. As such, you can't give them a time zone. If time zone is important, you'll need to track both the time and the time zone.

Ben Gottlieb
Thanks Ben for your answer. What I did to test your hypothesis is to remove the line with the setTimeZone. When I do I get a different result when using NSDate timeIntervalSinceDate for the current time. Maybe you are right that NSDate itself doesn't care about the timezone, but setting it using NSDateComponents gives different results based on if I have the setTimeZone there or not. Hope this makes sense?
Structurer
NSDateComponents does track the time zone... it's a much heavier-weight class than NSDate.
Ben Gottlieb
A: 

I wonder if you could set the time zone on the NSCalendar object that you use to create the NSDate from the NSDateComponents. I haven't tried this and don't know if it'll work, but it's probably worth a try.

Thomas Müller
Thanks! I just removed the setTimeZone for the comps and added one for the cal, [cal setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]]; and it works just fine giving me the same result. Great!
Structurer