Date Conversion from String?

Hi,


My Code Snippet:

var myDateFormat : DateFormatter = {

let fomat = DateFormatter()

fomat.dateFormat = "yyyy-MM-dd"

return fomat

}()



let selectedDateStr = "2018-08-01"

let selectedDate = self.myDateFormat.date(from: selectedDateStr)


The above code produces selectedDate as 2018-07-31 18:30:00 +0000

How to rectify this?

Replies

This is because of time conversion from UTC to locale.


You could change like this :


var myDateFormat : DateFormatter = {
    let fomat = DateFormatter()
    fomat.dateFormat = "yyyy-MM-dd"
    fomat.timeZone = TimeZone(abbreviation: "UTC")
    return fomat
}()


You'll get


2018-08-01 00:00:00 +0000


Take care, you have a type format instead of format

This is a surprisingly complex issue, so to provide a proper answer I need some background information. What’s your high-level goal here? Specifically, are you expecting

selectedDateStr
to be input by the user? Or is it a fixed-format string coming from file? Or a web service?

There’s a bunch of issues in play here. To start, if you’re dealing with a fixed-format date string you need to nail down the locale, as per QA1480 NSDateFormatter and Internet Dates. However, that’s not the full story when you’re dealing with a date string that doesn’t contain a time.

There’s a fundamental mismatch between such a date-only string and the Swift

Date
type. The latter represents a specific fixed point in time, so to convert the string
2018-08-01
to a
Date
, you must necessarily specify what time you care about.
DateFormatter
has its own way of doing this (via the
defaultDate
property) but that’s not always the right solution. In many cases it’s better to deal with date-only values using the
DateComponents
type and then only render them to a
Date
when you need to display them to the user.

Like I said, this is complex stuff. If you provide more background information we should be able to set you on the right path.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"