如何将String转换为NSDate?

编程入门 行业动态 更新时间:2024-10-18 06:11:10
本文介绍了如何将String转换为NSDate?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

每当有新的远程通知时,我都会收到字符串。我正在使用解析来查看我的后端。我检索的字符串来自createdAt列。

I have string that I received whenever there is new remote notifications.I'm using parse for my Backend. And String that I retrieved come from "createdAt" column.

我尝试过以下代码:

var ca = "2015-07-03T03:16:17.220Z" var dateFormater : NSDateFormatter = NSDateFormatter() dateFormater.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'" let date = dateFormater.dateFromString(ca) println(date)

但println给我零,我认为我的日期格式有问题。我该如何解决这个问题?

But the println is giving me nil, I think there is something wrong with my date format. How can I fix this?

推荐答案

你错过了毫秒。因此:

dateFormater.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

注意,从日期字符串转换为 NSDate ,你不应该引用 Z 。如果引用 Z ,它将匹配文字 Z 字符,但不会正确反映此日期字符串实际上是Zulu / GMT / UTC。

Note, when converting from the date string to a NSDate, you shouldn't quote the Z. If you quote the Z, it will match the literal Z character, but won't correctly reflect that this date string is actually Zulu/GMT/UTC.

如果你想创建另一种方式的格式化器,转换 NSDate 字符串对象,在这种情况下你应引用 Z ,但在这种情况下你必须记得明确设置时区:

If you want to create formatter that also goes the other way, converting NSDate objects to strings, in that case you should quote the Z, but in that case you must remember to explicitly set the timezone:

dateFormater.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" dateFormater.timeZone = NSTimeZone(forSecondsFromGMT: 0)

顺便说一下,不要忘记按区域设置 /qa1480/_index.htmlrel =nofollow> Apple Technical Q& A 1480 。

By the way, don't forget to set the locale as per Apple Technical Q&A 1480.

dateFormater.locale = NSLocale(localeIdentifier: "en_US_POSIX")

更多推荐

如何将String转换为NSDate?

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

发布评论

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

>www.elefans.com

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