Swift Date Formatting返回Nil

时间:2018-03-12 08:36:50

标签: swift datetime date-formatting

我试图在Sign Out按下时将标签设置为格式化的日期字符串。

let dateFormatterUK = DateFormatter()
let dateString : String = String(describing: Date())
dateFormatterUK.dateFormat = "dd-MM-yyyy"
let currentDateTime = dateFormatterUK.date(from: dateString)

以上是格式化Date的代码。但是,当我将标签设置为currentDateTime变量时,它会设置为Nil

1 个答案:

答案 0 :(得分:1)

试试这个:

let dateFormatterUK = DateFormatter()
dateFormatterUK.dateFormat = "dd-MM-yyyy"
let currentDateTime = dateFormatterUK.string(from: Date())

如果您的日期是字符串并想要更改格式:

let dateFormatterUK = DateFormatter()
dateFormatterUK.dateFormat = "dd-MM-yyyy"

let stringDate = "11-03-2018"
let date = dateFormatterUK.date(from: stringDate)!

// set new format
dateFormatterUK.dateFormat = "yyyy-MM-dd"
let currentDateTime = dateFormatterUK.string(from: date)