Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify the time offset with an NSDateFormatter (-0500)

I have some date strings similar to these:

2013-01-25 00:00:00 -0500
2013-01-22 00:00:00 -0700
2013-01-26 00:00:00 -0200

I want to use an NSDateFormatter to create an NSDate using these kinds of strings. I know how to use a formatter to get the first part of the date (2013-01-25 00:00:00), but I don't know how to specify the offset part (-0500, -0200, etc). Here's the code to get the start of the date string:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy'-'MM'-'dd HH':'mm':'ss"];
NSString *dateString = @"2013-01-25 00:00:00"; // <-------- Truncated ----
NSDate *date = [dateFormatter dateFromString:dateString];
NSLog(@"Date: %@", date);

How can I get it working with the -0500 part? I tried SSSZ, but it didn't work (gave a null date).

like image 359
nevan king Avatar asked May 02 '13 12:05

nevan king


1 Answers

Try this:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy'-'MM'-'dd HH':'mm':'ss ZZZ"];
NSString *dateString = @"2013-01-25 00:00:00 -0500";
NSDate *date = [dateFormatter dateFromString:dateString];
NSLog(@"Date: %@", date);

I get:

Date: 2013-01-25 05:00:00 +0000

As a side note, here is the standard for all date formats: http://unicode.org/reports/tr35/tr35-4.html#Date_Format_Patterns

like image 81
iwasrobbed Avatar answered Nov 01 '22 02:11

iwasrobbed