gpt4 book ai didi

Swift 相当于 C gmtime?

转载 作者:可可西里 更新时间:2023-11-01 00:55:33 25 4
gpt4 key购买 nike

将 C 代码迁移到 Swift,对应的等效代码是什么?

time(&CurrentTime);
tm = gmtime(&CurrentTime);
dayOfYear = tm->tm_yday + 1;
st = tm->tm_hour + tm->tm_min / 60.0 + tm->tm_sec / 3600.0;

我目前将其转换为以下内容,但我猜有些地方出了问题(可能是时间的开始?):

let currentTime = Date()

let calendar = Calendar.current

let hour = calendar.component(.hour, from: currentTime)
let min = calendar.component(.minute, from: currentTime)
let sec = calendar.component(.second, from: currentTime)

let dayOfYear = Double(calendar.ordinality(of: .day, in: .year, for: currentTime)!) + 1

let hHour = Double(hour)
let hMin = Double(min) / 60.0
let hSec = Double(sec) / 3_600.0

最佳答案

首先,您可以从 Swift 调用这些 C 库函数:

var currentTime = time(nil)
let tm = gmtime(&currentTime).pointee

let dayOfYear = tm.tm_yday + 1
let st = Double(tm.tm_hour) + Double(tm.tm_min) / 60.0 + Double(tm.tm_sec) / 3600.0

gmtime() 在不调整时区的情况下转换时间值。为了获得与 Calendar 相同的结果您必须将其时区设置为 GMT:

var calendar = Calendar.current
calendar.timeZone = TimeZone(secondsFromGMT: 0)!

calendar.ordinality(of:...) 的返回值是从一开始的,所以你不能添加 1:

let dayOfYear = calendar.ordinality(of: .day, in: .year, for:  currentTime)!

最后,您可以通过一次调用检索多个日期组件:

let comps = calendar.dateComponents([.hour, .minute, .second], from: currentTime)
let st = Double(comps.hour!) + Double(comps.minute!)/60 + Double(comps.second!)/3600

关于Swift 相当于 C gmtime?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49521163/

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