Swift中的日期格式 [英] Date Format in Swift
本文介绍了Swift中的日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何从日期转换此日期时间?
How will I convert this datetime from the date?
来自:2016-02-29 12:24:26
到:2016年2月29日
到目前为止,这是我的代码,它返回零值:
So far, this is my code and it returns a nil value:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let date: NSDate? = dateFormatter.dateFromString("2016-02-29 12:24:26")
print(date)
推荐答案
你必须声明2个不同的 NSDateFormatters
,第一个将字符串转换为 NSDate
和第二个用你的格式打印日期。
试试这个代码:
You have to declare 2 different NSDateFormatters
, the first to convert the string to a NSDate
and the second to print the date in your format.
Try this code:
let dateFormatterGet = NSDateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateFormatterPrint = NSDateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
let date: NSDate? = dateFormatterGet.dateFromString("2016-02-29 12:24:26")
print(dateFormatterPrint.stringFromDate(date!))
Swift 4:
在Swift 3/4 NSDate
类已更改为日期
和 NSDateFormatter
到 DateFormatter
。
In Swift 3/4 NSDate
class has been changed to Date
and NSDateFormatter
to DateFormatter
.
let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"
if let date = dateFormatterGet.date(from: "2016-02-29 12:24:26"){
print(dateFormatterPrint.string(from: date))
}
else {
print("There was an error decoding the string")
}
这篇关于Swift中的日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文