Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
667 views
in Technique[技术] by (71.8m points)

date - 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!)
println(dateString)

Output

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can set your DateFormatter amSymbol and pmSymbol as follow:

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
"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...