Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a date string like "2011-01-12T14:17:55.043Z" to a long like 1294841716?

I need to convert a date in this string format:

"2011-01-12T14:17:55.043Z"

to a number like 1294841716 (which is the number of seconds [not milliseconds] since Jan. 1st, 1970). Is there an easy way to do this parsing?

Update: Here is the code I've got so far:

NSString *dateString = @"2011-01-12T14:17:55.043Z";
NSDateFormatter *inFormat = [[NSDateFormatter alloc] init];
[inFormat setDateFormat:@"yyyy-MM-ddTHH:mm:ss.nnnZ"];
NSDate *parsed = [inFormat dateFromString:dateString];
long t = [parsed timeIntervalSinceReferenceDate];

But t comes back as 0 every time.

like image 369
MusiGenesis Avatar asked Dec 03 '22 03:12

MusiGenesis


1 Answers

Use NSDateFormatter to get a NSDate then use - (NSTimeInterval)timeIntervalSince1970 to get the seconds since 1970.

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
NSDate *date = [formatter dateFromString:@"2011-01-12T14:17:55.043Z"];
NSLog(@"Date: %@", date);
NSLog(@"1970: %f", [date timeIntervalSince1970]);
NSLog(@"sDate: %@", [formatter stringFromDate:date]);
[formatter release];
like image 113
Joe Avatar answered Feb 06 '23 21:02

Joe