How to convert string to date without time in Swift 3?

孤者浪人 提交于 2020-01-03 18:58:10

问题


I have try to convert the date like 2017-02-11 string to date but the result give me back something like this 2017-02-10 16:00:00 +0000 . I am using the following code below.

let localDate = dateFormatter.string(from: date) //2017-02-11

    let dateFormatter2 = DateFormatter()
    dateFormatter2.dateFormat = "yyyy-MM-dd"

    let selectedDate = dateFormatter2.date(from: localDate)
    print("Did Select \(selectedDate)") // 2017-02-10 16:00:00 +0000

回答1:


let dateWithTime = Date()

let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short

let date = dateFormatter.string(from: dateWithTime) // 2/10/17

This will format it correctly, but this will be for display purposes only. All Dates have time.




回答2:


It's true that there is no Date without a time element, but if you need something that you can use to compare whole days, you can get the first moment of a given Date using

Calendar.current.startOfDay(for: dateWithTime)


来源:https://stackoverflow.com/questions/42464197/how-to-convert-string-to-date-without-time-in-swift-3

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