日期/时间格式化Swift

时间:2018-04-26 16:06:53

标签: ios swift xcode

我试图将以下日期/时间转换为:" 04-26-2018 10:17 AM" 格式为:" 2018-04-26T10:17"

这是我的代码:

let myDateString = "04-26-2018 10:17 AM"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy HH:mm a"

let myDate = dateFormatter.date(from: myDateString)!
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm"
let somedateString = dateFormatter.string(from: myDate)

somedateString的输出是" 2018-04-26T00:17" 这是不正确的..我的代码中有什么问题吗?

1 个答案:

答案 0 :(得分:1)

您只需要DateFormatter MM-dd-yyyy HH:mm aMM-dd-yyyy hh:mm a

即可
let myDateString = "04-26-2018 10:17 AM"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy hh:mm a"

let myDate = dateFormatter.date(from: myDateString)!
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm"
let somedateString = dateFormatter.string(from: myDate)