Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting an NSDate to specific date, time and timezone

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...

like image 548
Structurer Avatar asked Sep 07 '10 03:09

Structurer


2 Answers

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.

like image 198
Thomas Müller Avatar answered Oct 21 '22 14:10

Thomas Müller


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.

like image 27
Ben Gottlieb Avatar answered Oct 21 '22 16:10

Ben Gottlieb