Jazzmine
Jazzmine

Reputation: 1875

Getting correct NSDate value - is this the most efficient method?

I have this code to get the local date/time. It works but it seems a long way around the bush (10 statements) to get my current date/time value rather than the GMT time.

NSDate          *currentDateGMT = [NSDate date];
NSDateFormatter *currentDateDateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone      *currentDateTimeZoneGMT = [NSTimeZone timeZoneWithName:@"GMT"];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];

[currentDateDateFormatter setTimeZone: currentDateTimeZoneGMT];
[currentDateDateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
[currentDateDateFormatter setLocale:locale];

NSString *currentDateString = [currentDateDateFormatter stringFromDate:currentDateGMT];
NSDate *currentDateAdjusted = [currentDateDateFormatter dateFromString:currentDateString]; 

[currentDateDateFormatter release];

Can someone confirm that this is the best way to obtain the current machine value?

Thanks

Upvotes: 1

Views: 533

Answers (1)

Joe
Joe

Reputation: 57179

NSDateFormatter will default to the users time zone so the simplest solution is

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//lower case h for hour will also default to the users
//12/24 hour clock preference
[formatter setDateFormat:@"yyyy-MM-dd hh:mm"];

NSString *currentDate = [formatter stringFromDate:[NSDate date]];

[formatter release];

Upvotes: 1

Related Questions