Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

iOS Swift – Trying to convert a String to Date. Which is the correct dateFormat for this date? Sun, 01 Oct 2023 00:00:00 GMT

I’m trying to convert a String into a Date object. The String contains a date in this format "Sun, 01 Oct 2023 00:00:00 GMT".

What i did is this:

let formatter = DateFormatter()
formatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z"
formatter.timeZone = TimeZone(abbreviation: "UTC")


// dateObject -> Date / StringDate -> String       
item.dateObject = item.stringDate?.toDate(formatter: formatter)

// toDate method
extension String {

func toDate(formatter: DateFormatter) -> Date? {
    if let dateFromString = formatter.date(from: self) {
            return dateFromString
    } else {
        return nil
    }
 }
}

But unfortunately item.dateObject is nil. I’ve put a breakpoint in the toDate method and it stops to "return nil". Is the dateFormat correct for that type of date?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks.

>Solution :

The format "E, d MMM yyyy HH:mm:ss Z" is valid for Sun, 01 Oct 2023 00:00:00 GMT

Some notes:

  1. A two digit day is actually dd.
  2. Specifying the time zone of the formatter is redundant since it’s part of the time string.
  3. According to the Unicode specifications the pattern for a three letter zone identifier is lowercase z.
  4. It’s highly recommended to specify a fixed Locale when applying a custom date format.

let timeString = "Sun, 01 Oct 2023 00:00:00 GMT"

let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "E, dd MMM yyyy HH:mm:ss z"
if let date = formatter.date(from: timeString) {
    print(date)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading