Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone NSDateFormatter Timezone Conversion

I am trying to create a formatter that will convert the date format shown to an NSDate object:

NSString *dateStr = @"2010-06-21T19:00:00-05:00";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZ"];
NSDate *date = [dateFormat dateFromString:dateStr];  

The issue is the timezone -05:00, which is not parsed properly with the format above. Any suggestions?

like image 371
John Muchow Avatar asked Jun 22 '10 15:06

John Muchow


3 Answers

To process the time zone with the colon in it, you just need to use 5 'Z's. This is a pretty common date format, the ISO-8601 format. This will only work on iOS 6.x+

-(NSDate *) dateFromString:(NSString *)string {

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];

    return [formatter dateFromString:string];
}
like image 114
brynbodayle Avatar answered Oct 20 '22 18:10

brynbodayle


Honestly, you'll just have to change the source data (removing the colon) before running it through the formatter. Your original date string is non-standard and none of the time zone format strings will work properly on it.

You can see the valid inputs on unicode.org.

ZZZ e.g. "-0500"

ZZZZ e.g. "GMT-05:00"

Nothing for "-05:00"

like image 31
chrissr Avatar answered Oct 20 '22 18:10

chrissr


May be I missed something but ZZ worked for me. I used:

@"yyyy-MM-dd'T'HH:mm:ss.SSSZZ"

for

2014-02-27T08:00:00.000+04:00
like image 3
DanSkeel Avatar answered Oct 20 '22 19:10

DanSkeel