Amit Raj Amit Raj - 4 months ago 6
Swift Question

Show AM/PM in capitals in swift

I wrote the following code to show a datetime in a particular format:

let formatter = NSDateFormatter()
formatter.dateStyle = NSDateFormatterStyle.LongStyle
formatter.timeStyle = .MediumStyle
formatter.dateFormat = "HH:mm a 'on' MMMM dd, yyyy"
let dateString = formatter.stringFromDate(newDate!)


12:16 pm on July 17, 2015

I want to show 'pm' as 'PM'(in capitals) and if phone has 24 hours format then AM/PM should not appear. Please help me.


You can set your NSDateFormatter AMSymbol and PMSymbol as follow:

let formatter = NSDateFormatter()
formatter.dateFormat = "h:mm a 'on' MMMM dd, yyyy"
formatter.AMSymbol = "AM"
formatter.PMSymbol = "PM"

let dateString = formatter.stringFromDate(NSDate())
println(dateString)   // "3:11 AM on July 17, 2015"

Xcode 8 beta • Swift 3

let formatter = DateFormatter()
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"