Search code examples
swifttimezonegmtlocaltime

GMT to local time conversion ERROR with swift UIKIT


Does anyone have an answer to why I am getting -8 hours instead of -7 (my timezone) hours difference upon converting time from GMT to local i using the formula below:

print("TIMEZONE IN HOURS: \(timeZone/3600)")
        
let interval = Date(timeIntervalSinceReferenceDate: 93866.4142533315)
print("GMT TIME: \(interval)")
        
let intervalDateComponents = calendar.dateComponents([.hour, .minute, .second], from: interval)
let mHour = intervalDateComponents.hour ?? 0
let mMinute = intervalDateComponents.minute ?? 0
print("INTERVAL DATE COMPONENT: \(intervalDateComponents)")
    
let formatter = DateFormatter()
        
formatter.timeZone = TimeZone.current
        
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        
let intervalDateString = formatter.string(from: interval)
        
print("DATE STRING FORMAT: \(intervalDateString)")
        

prints out the following: (please pay attention to date)

TIMEZONE IN HOURS: -7
GMT TIME: 2001-01-02 02:04:26 +0000 (January 2)
INTERVAL DATE COMPONENT: hour: 18 minute: 4 second: 26 isLeapMonth: false 
DATE STRING FORMAT: 2001-01-01 18:04:26 (January 1)
interval HOURS: 18

edit/update:

let mDateString = formatter.string(from: interval) 
print("DATE STRING FORMAT: (mDateString)")
let mdate = formatter.date(from: mDateString) 
print("MDATE: (mdate)")
let mDateComponents = calendar.dateComponents([.hour, .minute, .second], from: mdate!)
print("M DATE COMPONENT: (mDateComponents)")

prints out:

DATE STRING FORMAT: 2001-01-01 19:01:27 -0700 
MDATE: Optional(2001-01-02 02:01:27 +0000)
M DATE COMPONENT: hour: 18 minute: 1 second: 27 isLeapMonth: false 

If you notice above in the code my intention is to extract the local time component to trigger alarm at a later time daily. So I fed the string that shows

2001-01-01 19:01:27 -0700

I converted the string to mdate in order to get time components that I need to use for the alarm to work on time so I got (hour: 18) rather than hour: 19 which I used to generate the mdate string.


Solution

  • The problem there is that you are getting the timezone offset for today. You need to get the timezone offset for the same date you are using:

    let timeZone = TimeZone.current.secondsFromGMT(for: interval)
    print("TIMEZONE IN HOURS: \(timeZone/3600)")