Swift-C函数和struct-tm

Swift-C函数和struct-tm,swift,Swift,我有一个Swift程序,它使用C API。我的一个API方法返回struct tm。有没有办法,如何将它转换为Swift日期,或者我必须自己在C端解析它,然后手动将部分传递给Swift?我不知道Swift标准库中有内置函数。但您可以使用C库中的timegm(),如中所述: 然后可以用作 if let date = Date(tm: yourStructTmVariable) { print(date) } else { print("invalid value") } 另一种可

我有一个Swift程序,它使用C API。我的一个API方法返回
struct tm
。有没有办法,如何将它转换为Swift日期,或者我必须自己在C端解析它,然后手动将部分传递给Swift?

我不知道Swift标准库中有内置函数。但您可以使用C库中的
timegm()
,如中所述:

然后可以用作

if let date = Date(tm: yourStructTmVariable) {
    print(date)
} else {
    print("invalid value")
}
另一种可能的方法是用 使用
struct tm
中的值,并使用
Calendar
将其转换为 a
日期

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
    }
}
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
    }
}