以正确的方式从Int构建日期

问题描述 投票:1回答:1

所以我从后端得到这个答案:

{ "SERVERDateTimeGet": { "Return Code" : 0,
    "Return String" : "No Error",
    "Year" : 2018,
        "Month" : 8,
        "Day" : 29,
        "Hour" : 14,
        "Minute" : 16,
        "Second" : 20,
        "Daylight" : 1,
        "NTP" : 0,
        "NtpDhcp" : 0,
        "NtpServers" : "time.google.com",
        "Timezone" : "EET-2EEST,M3.5.6/0:01,M9.1.5" }
 }

(我知道这很糟糕,非常糟糕,但是那时我才得到)

我有这个方法:

func makeDate(year: Int, month: Int, day: Int, hr: Int, min: Int, sec: Int) -> Date {
    let calendar = Calendar(identifier: .gregorian)
   // calendar.timeZone = TimeZone.current
    let components = DateComponents(year: year, month: month, day: day, hour: hr, minute: min, second: sec)
    //let components = DateComponents(timeZone: TimeZone.current, year: year, month: month, day: day, hour: hr, minute: min, second: sec)
    return calendar.date(from: components)!
}

但是当我得到约会时它是3个小时。我认为这是因为时区,但你可以看到我没有使用时区。有没有其他方法来建立日期或只使用当前的整数?

swift date nsdate nsdatecomponents
1个回答
2
投票

如果您没有设置TimeZone,这意味着您的时间将是UTC,因此您有-3小时的差距。要获得正确的值,您需要配置TimeZone。你可以检查一下here

© www.soinside.com 2019 - 2024. All rights reserved.