Deekshith Bellare
Deekshith Bellare

Reputation: 735

Covert string with timezone to Date

Here is the date string

NSString * dateString = @"Mon Sep 29 14:40:00 2014 PET";

How to convert it into NSDate?

NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
[dateFormatter setCalendar:[NSCalendar currentCalendar]];
[dateFormatter setDateFormat:@"EEE MMM dd HH:mm:ss yyyy zzz"];
NSDate* date = [dateFormatter dateFromString:dateString];

Above code doesn't work. what is the correct date format for above case?

Upvotes: 1

Views: 87

Answers (1)

holex
holex

Reputation: 24031

the problem is your timezone definition (PET), because that is not on list of the recognisable timezones (please don't ask why not); this timezone is mostly known as UTC-5 in Apple's system, therefore:


NSString *_dateString = @"Mon Sep 29 14:40:00 2014 PET";
_dateString = [_dateString stringByReplacingOccurrencesOfString:@"PET" withString:@"UTC-5"];
NSDateFormatter *_dateFormatter = [[NSDateFormatter alloc] init];
[_dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"]];
[_dateFormatter setCalendar:[NSCalendar currentCalendar]];
[_dateFormatter setDateFormat:@"EEE MMM dd HH:mm:ss yyyy zzz"];
NSDate *_date = [_dateFormatter dateFromString:_dateString];
NSLog(@"date : %@", _date);

and the console says:

date : 2014-09-29 19:40:00 +0000

which is the correct representation of the original date in GMT+0 timezone.

Upvotes: 2

Related Questions