如何使用Swift格式化JSON日期字符串? [英] How do I format JSON Date String with Swift?
问题描述
我向服务器发出http get请求,并返回带有日期字符串的json对象,如下所示:
I make an http get request to a server and get back a json object with a date string like this:
{
name = "Place1";
temperature = 79;
humidity = 68;
reported_at = "2013-07-21T19:32:00Z";
}
我想格式化reported_at键,以便向用户显示可读的日期和时间.
I want to format the reported_at key so I can display a readable date and time to the user.
这是我正在尝试的快速代码,该代码一直返回nil,因为它无法格式化日期.
This is the swift code I am trying which keeps returning nil, as it cannot format the date.
var str = "2013-07-21T19:32:00Z"
var dateFor: NSDateFormatter = NSDateFormatter()
dateFor.dateFormat = "yyyy-MM-dd'T'HH:mm:ss:SSS"
var yourDate: NSDate? = dateFor.dateFromString(str)
println(yourDate)
如何使用Swift正确格式化日期和时间?我想向用户显示日期和时间,以便他们可以知道何时进行阅读.
How can I format this date and time with Swift correctly? I want to display the date and time to the user so they can know when the reading was taken.
推荐答案
使用以下字符串格式将服务器字符串转换为Date
Use the following string format to convert a server string into a Date
dateFor.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
这篇关于如何使用Swift格式化JSON日期字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!