iosswiftdatetimensdatensdateformatter

Set current time to yyyy-MM-dd 00:00:00 using Swift


I want to ask about NSDate, how to set/format current time like "2015-08-12 09:30:41 +0000" to "2015-08-12 00:00:00 +0000

I'm already using :

var dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .MediumStyle
dateFormatter.timeStyle = .NoStyle
//result date will be : Aug 12, 2015

but the value date is not stored in the Database exactly as "2015-08-12 00:00:00 +0000" but storing as "2015-08-11 17:00:00 +0000 UTC"


Solution

  • Swift 4 or later

    let dateString = "2019-05-04 09:30:41 +0000"
    let dateFormatter = DateFormatter()
    dateFormatter.calendar = Calendar(identifier: .gregorian)
    dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    dateFormatter.dateFormat = "yyyy-MM-dd"
    if let dateFromString = dateFormatter.date(from: dateString.components(separatedBy: " ").first ?? "") {
        print(dateFromString)  // "2019-05-04 00:00:00 +0000"
    }