Search code examples
iosswiftdatetimestandard-librarydarwin

Date in darwin standard library giving me the wrong date?


What is wrong with this code in swift accessing the time and date functions in C? The date it gives me is off by 3 days even though the difftime function is correct on the time difference.

 import Darwin
    var time1 = tm(tm_sec: 00, tm_min: 00, tm_hour: 00, tm_mday: 13, tm_mon: 06, tm_year: 1977, tm_wday: 0, tm_yday: 0, tm_isdst: 0, tm_gmtoff: 0, tm_zone: nil)
    var time1secs = timegm(&time1)
    var time2secs = timegm(&time1) + 1_000_000_000
    var time2 = gmtime(&time2secs).memory

    difftime(time2secs, time1secs) // 1,000,000,000
    print("\(time2.tm_year)-\(time2.tm_mon)-\(time2.tm_mday)") //2009-2-22

    // The correct answer is 2009-02-19

Solution

  • In the struct tm, the tm_year field is the number of years since 1900, and tm_mon is the month in the range 0 .. 11:

    // struct tm for 1977/06/13:
    var time1 = tm()
    time1.tm_year = 1977 - 1900
    time1.tm_mon = 06 - 1
    time1.tm_mday = 13
    
    // Add 10^9 seconds:
    var time2secs = timegm(&time1) + 1_000_000_000
    var time2 = gmtime(&time2secs).memory
    
    // Extract year/month/day:
    let year = time2.tm_year + 1900
    let month = time2.tm_mon + 1
    let day = time2.tm_mday
    print("\(year)-\(month)-\(day)") // 2009-2-19