Search code examples
iosswiftdatedateformatter

String to date conversion sometimes returns nil with DateFormatter


I just read over this post which details that you need to set a locale before the format before attempting to convert a given string back to a date.

I have the below code that follows that format but the conversion from string to date still seems to return nil though in the playground it seems to work fine.

// originalDate style is the .full style, "Friday, December 10, 2021 at 4:17:04 PM Pacific Standard Time"
let df: DateFormatter = DateFormatter()
df.locale = Locale(identifier: "en_US_POSIX")
df.dateFormat = "MMM d, yyyy" // Sep 12, 2018 format'

let newDate = df.date(from: originalDate)
let newStringDate = df.string(from: newDate!) // throws found nil when unwrapping

What could be causing this?

Edit 1: I'm pulling a string type out of a sqlite db using SQLite.swift


Solution

  • Answer for your question (string to date is nil): While converting from string to date, you have to use the same format as String. I assume the originalDate from your comments. You have to change your code like this

    let originalDate = "Friday, December 10, 2021 at 4:17:04 PM"
    let df: DateFormatter = DateFormatter()
    df.locale = Locale(identifier: "en_US_POSIX")
    df.dateFormat = "EEEE, MMMM d, yyyy 'at' h:mm:ss a"
    
    let newDate = df.date(from: originalDate)
    print(newDate)
    

    If you again want string from date then you can again specify which format you want.

    df.dateFormat = "MMM d, yyyy" // Sep 12, 2018 format'
    let newStringDate = df.string(from: newDate!)
    print(newStringDate)
    

    Note: If you try to log the newDate value in the console using print, sometimes it shows nil. In that case, you can try 'po newDate' in the console.