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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With