Search code examples
swiftstringdatedateformatter

Swift dateformatter.date(from: string) strange behaviour


import UIKit

let dateString="2018.03.11"

let df = DateFormatter()

df.timeZone=TimeZone(secondsFromGMT: 0)
df.dateFormat="YYYY.MM.dd"

let date=df.date(from: dateString)

print("orig dateString: \(dateString)")
print("date(from: string): \(date)")
print("converted again: \(df.string(from: date!))")

now this code seems to work as expected. Both input and output dates are the same: orig dateString: 2018.03.11

date(from: string): Optional(2018-03-11 00:00:00 +0000)

converted again: 2018.03.11

But if I try to change the input format:

import UIKit

    let dateString="11.03.2018"

    let df = DateFormatter()

    df.timeZone=TimeZone(secondsFromGMT: 0)
    df.dateFormat="dd.MM.YYYY"


    let date=df.date(from: dateString)

    print("orig dateString: \(dateString)")
    print("date(from: string): \(date)")
    print("converted again: \(df.string(from: date!))")

I get the following result:

orig dateString: 11.03.2018

date(from: string): Optional(2017-12-24 00:00:00 +0000)

converted again: 24.12.2017

The date(from: String) seems to initialize the date in a way that I do not understand. Any help appreciated. Thank you.


Solution

  • The problem is with the date format.

    change these lines:

    df.dateFormat="YYYY.MM.dd"
    df.dateFormat="dd.MM.YYYY"
    

    to this:

    df.dateFormat="yyyy.MM.dd"
    df.dateFormat="dd.MM.yyyy"