gpt4 book ai didi

ios - Darwin 标准库中的日期给我错误的日期?

转载 作者:行者123 更新时间:2023-11-28 06:58:41 24 4
gpt4 key购买 nike

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

 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

最佳答案

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

关于ios - Darwin 标准库中的日期给我错误的日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32640425/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com