Search code examples
swiftdatensdatensdatecomponents

Constructing date from Int the right way


So i get from the backend this answer :

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

(I know this is bad ,very bad but for the time that is what i get)

I have this method :

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

but when i get the date it is 3 hours back. I assume that this is because the time zone , but as you can see i am not using the time zone. Is there any other way to build date or just use the current ints?


Solution

  • If you don't set TimeZone, that means your time will be in UTC, so you have -3 hours gap. To get the right value you need configure TimeZone. You can check it here