将AM或PM设置为日期

时间:2017-07-26 09:56:17

标签: swift

var dateComponents: DateComponents = (Calendar.current as NSCalendar).components([NSCalendar.Unit.day, NSCalendar.Unit.month, NSCalendar.Unit.year, NSCalendar.Unit.hour, NSCalendar.Unit.minute, NSCalendar.Unit.second], from: dateToFix)
dateComponents.hour = 11
dateComponents.minute = 58
dateComponents.second = 00

let fixedDate: Date = Calendar.current.date(from: dateComponents)!
print(fixedDate)

let formatter = DateFormatter()
formatter.dateStyle = DateFormatter.Style.long
formatter.timeStyle = DateFormatter.Style.medium
formatter.dateFormat = "yyyy-MM-dd h:mm a"
let dateString = formatter.string(from: fixedDate)
print(dateString)
  

我的输出:2017-07-26 11:58 AM但我希望2017-07-26 11:58 PM

2 个答案:

答案 0 :(得分:3)

更改:

dateComponents.hour = 11

dateComponents.hour = 23

答案 1 :(得分:0)

确实将dateComponents.hour更改为24小时值,因为它希望您提供1-24位数字。

文档说:

enter image description here