-1
我有Swift程序,它使用C API。我的一個API方法返回struct tm
。有沒有辦法,如何將其轉換爲Swift Date或者我必須在C端自己解析它,並將部分手動傳遞給Swift?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
}
}