我编写了以下代码以特定格式显示日期时间:
let formatter = NSDateFormatter() formatter.dateStyle = NSDateFormatterStyle.LongStyle formatter.timeStyle = .MediumStyle formatter.dateFormat = "HH:mm a 'on' MMMM dd, yyyy" let dateString = formatter.stringFromDate(newDate!) println(dateString)
输出量
12:16 pm on July 17, 2015
我想将“ pm”显示为“ PM”(用大写字母表示),如果电话具有24小时格式,则AM / PM应该不会出现。请帮我。
您可以如下设置DateFormatter amSymbol和pmSymbol:
Xcode 8.3•Swift 3.1
let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.dateFormat = "h:mm a 'on' MMMM dd, yyyy" formatter.amSymbol = "AM" formatter.pmSymbol = "PM" let dateString = formatter.string(from: Date()) print(dateString) // "4:44 PM on June 23, 2016\n"