问题
I am trying to print a date (e.g. a birthdate) using the following code (swift 4.0, Xcode 10.2):
let formatter = DateFormatter()
formatter.timeStyle = .short
formatter.dateStyle = .short
formatter.locale = Locale(identifier: "en_US")
formatter.dateFormat = "yyyy/MM/dd HH:mm"
let DOB = formatter.date(from: "2019/05/01 22:30")
when print(DOB) I got, "2019-05-02 05:30:00 +0000"
It looks like none of the Local, .short settings affected the results.
What's wrong. How do I get to simply print: "2019/05/01 22:30"?
回答1:
What you are currently doing is converting a string to a Date. Dates don't contain information about how they are displayed. They are printed all the same way: 2019-05-02 05:30:00 +0000.
Strings have formats, so you should convert the Date you just got, back to a string using a date formatter. Basically, you have two formatters: one for converting the string to a date, and another for converting the date back to a string
let stringToDateformatter = DateFormatter()
stringToDateformatter.dateFormat = "yyyy/MM/dd HH:mm"
let DOB = stringToDateformatter.date(from: "2019/05/01 22:30")
let dateToStringFormatter = DateFormatter()
dateToStringFormatter.timeStyle = .short
dateToStringFormatter.dateStyle = .short
dateToStringFormatter.locale = Locale(identifier: "en_US")
let DOBString = dateToStringFormatter.string(from: DOB!)
print(DOBString) // 5/1/19, 10:30 PM
回答2:
let formatter = DateFormatter()
formatter.timeStyle = .short
formatter.dateStyle = .short
formatter.locale = Locale(identifier: "en_US")
formatter.dateFormat = "yyyy/MM/dd HH:mm"
let DOB = formatter.date(from: "2019/05/01 22:30")
formatter.dateFormat = "yyyy/MM/dd HH:mm"
let createdDate = formatter.string(from: DOB!)
来源:https://stackoverflow.com/questions/55946786/how-do-i-get-the-short-local-date-time-format-with-swift-4-0