How do I get the short, local date/time format with Swift 4.0?

不羁岁月 提交于 2021-01-28 11:56:38

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!