Search code examples
iosswift3nsdateformatterunix-timestamp

timeIntervalSince1970 conversion returns the wrong year in Swift 3


I'm facing a problem that timeIntervalSince1970 returns the wrong year.

Here is my code

func unixToDateString(timeStamp: TimeInterval) -> String {
    let date = Date(timeIntervalSince1970: timeStamp)
    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier:Locale.current.identifier)
    dateFormatter.dateFormat = "MM/dd/YYYY"
    return dateFormatter.string(from: date)
}

and these are my results

unixToDateString(timeStamp: 1505896961.0)

returns

09/20/2017

which is correct

but,

unixToDateString(timeStamp: 1546214400.0)
unixToDateString(timeStamp: 4133894400.0)

returns

12/31/2019
12/31/2101

they both return extra one year according to Epoch Unix Time Stamp Converter

1546214400.0 = 12/31/2018
4133894400.0 = 12/31/2100

Does anyone have the same situation?


Solution

  • The problem is that the date format uses "Year (of "Week of Year")" (YYYY) but the result you are expecting is "Calendar Year" (yyyy).

    After changing the date format to "MM/dd/yyyy", I'm seeing results that you are expecting (the years 2018 and 2100).


    You can see both Y and y listed in the Unicode Standard Date Field Symbol Table. In their example, the Year of "Week of Year" (1997) is also one more than the Calendar Year (1996).

    The Data Formatting Guide also brings up the same problem and points out that one should typically use the calendar date (yyyy):

    A common mistake is to use YYYY. yyyy specifies the calendar year whereas YYYY specifies the year (of “Week of Year”), used in the ISO year-week calendar. In most cases, yyyy and YYYY yield the same number, however they may be different. Typically you should use the calendar year.