Constructing date from Int the right way
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?
makeDate
Your code works perfectly fine on the playgrounds. Check your input to the method.
– Rakesha Shastri
Aug 30 at 7:31
if you not set time zone it take default device timezone.
– Sagar Bhut
Aug 30 at 7:34
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 stackoverflow.com/questions/1862905/nsdate-convert-date-to-gmt
– gaRik
Aug 30 at 7:51
@gaRik thanks, you were right. i just needed to make it local time. do you want to write that as an answer?
– ironRoei
Aug 30 at 8:03
1 Answer
1
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
That explained why i always got it 3 hour back. i did that method from the link you gave: func toLocalTime() -> Date let timezone = TimeZone.current let seconds = TimeInterval(timezone.secondsFromGMT(for: self)) return Date(timeInterval: seconds, since: self) works like a charm:) thanks!
– ironRoei
Aug 30 at 8:08
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
What do you mean by "the date is 3 hours back"? How did you find out the difference of 3 hours? Please edit the question and provide the
makeDatecall with parameters– Andreas Oetjen
Aug 30 at 7:30