如何将像“2011

编程入门 行业动态 更新时间:2024-10-28 15:29:16
如何将像“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];

更多推荐

本文发布于:2023-08-07 19:36:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1465794.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何将

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!