达尔文标准库中的日期给我错误的日期?

时间:2015-09-17 21:42:28

标签: ios swift datetime standard-library darwin

在快速访问C中的时间和日期函数时,此代码有什么问题?它给我的日期是3天,即使difftime函数在时差上是正确的。

 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

1 个答案:

答案 0 :(得分:1)

struct tm中,tm_year字段是年数 自1900年以来,tm_mon是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