Swift相当于C gmtime?

时间:2018-03-27 19:39:39

标签: swift date

将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

2 个答案:

答案 0 :(得分:2)

首先,你可以从Swift中调用那些C库函数:

d

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()获得相同的结果 你必须将时区设置为GMT:

Calendar

var calendar = Calendar.current calendar.timeZone = TimeZone(secondsFromGMT: 0)! 的返回值是一个基础, 所以你不能添加calendar.ordinality(of:...)

1

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

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

答案 1 :(得分:1)

看起来你正试图获得自一天开始(GMT)以来的浮点小时数。您也可以通过以下方式实现这一目标:

var calendar = Calendar.current
calendar.timeZone = TimeZone(secondsFromGMT: 0)!
let now = Date()
let startOfDay = calendar.startOfDay(for: now)
let hours = now.timeIntervalSince(startOfDay) / 60 / 60