Swift - C函数和struct tm
问题描述:
我有Swift程序,它使用C API。我的一个API方法返回struct tm
。有没有办法,如何将其转换为Swift Date或者我必须在C端自己解析它,并将部分手动传递给Swift?Swift - C函数和struct tm
答
我不知道Swift标准库中的内置函数。但可以使用timegm()
脱离如C: Converting struct tm times with timezone to time_t描述的C库:
extension Date {
init?(tm: tm) {
let gmtOffset = tm.tm_gmtoff // Save the offset because timegm() modifies it
var tm = tm // A mutable copy
var time = timegm(&tm) // The time components interpreted as GMT
if time == -1 { return nil } // timegm() had an error
time -= gmtOffset // Adjustment for actual time zone
self.init(timeIntervalSince1970: TimeInterval(time))
}
}
然后可以从struct tm
并用作
if let date = Date(tm: yourStructTmVariable) {
print(date)
} else {
print("invalid value")
}
另一种可能的方法是填充DateComponents
结构与 值请使用Calendar
将其转换为 a Date
:
extension Date {
init?(tm: tm) {
let comps = DateComponents(year: 1900 + Int(tm.tm_year),
month: 1 + Int(tm.tm_mon),
day: Int(tm.tm_mday),
hour: Int(tm.tm_hour),
minute: Int(tm.tm_min),
second: Int(tm.tm_sec))
var cal = Calendar(identifier: .gregorian)
guard let tz = TimeZone(secondsFromGMT: tm.tm_gmtoff) else { return nil }
cal.timeZone = tz
guard let date = cal.date(from: comps) else { return nil }
self = date
}
}