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

I need to convert the date to this string format:

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

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

Update: Here is the code that I still have:

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 returns as 0 every time.

+4
source share
1 answer

Use NSDateFormatter to get NSDate , then use - (NSTimeInterval)timeIntervalSince1970 to get 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]; 
+18
source

Source: https://habr.com/ru/post/1337202/


All Articles