Swift 中的日期格式 [英] Date Format in Swift
本文介绍了Swift 中的日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将如何从日期转换此日期时间?
How will I convert this datetime from the date?
来自:2016-02-29 12:24:26
至:2016 年 2 月 29 日
From this: 2016-02-29 12:24:26
to: Feb 29, 2016
到目前为止,这是我的代码,它返回一个 nil 值:
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 3 及更高版本:
从 Swift 3 NSDate
类已更改为 Date
和 NSDateFormatter
到 DateFormatter
.
From Swift 3 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屋!
查看全文