如何将像“2011-01-12T14:17:55.043Z”这样的日期字符串转换为像1294841716那么长的日期字符串?(How to convert a date string like “2011-01-12T14:17:55.043Z” to a long like 1294841716?)
我需要以这种字符串格式转换日期:
“2011-01-12T14:17:55.043Z”
到1294841716这个数字(这是自1970年1月1日以来的秒数[不是毫秒])。 有没有简单的方法来做这个解析?
更新:这是我到目前为止的代码:
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];但是t每次都会回到0。
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.
最满意答案
使用NSDateFormatter获取NSDate然后使用- (NSTimeInterval)timeIntervalSince1970获取自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];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];更多推荐
发布评论