Search code examples
iosswiftnsdateformattertimezone-offsetxcode12

How to get store opening hours in local timezone from given date-time response? - SWIFT 5


I'm getting opening hours from Json response and I want to calculate if store is open or not at the moment?

My Json response is looks like this:

{
"endDay":2,
"endTime":"03:00",
"startDay":1,
"startTime":"11:00"
},
{
"endDay":3,
"endTime":"03:00",
"startDay":2,
"startTime":"11:00"
},
...

I have 7 dictionaries (Sunday to Monday) in this Json response, where startDay and endDay is representing weekday. (Sunday = 0, and so on.)

Above all times are in UTC, but I want to calculate in my local timezone.

Actual problem is figuring out the difference in 'Day' conversion. I can convert just time, but don't have idea how to manage the timezone difference in calculating next Day or previous day?

I'm using XCode 12 and Swift 5. Appreciate your help in advance. Thanks.


Solution

  • Here is conversion of weekday and time in GMT into PST time zone:

    let weekday = 2 // weekday == 1 is Sunday
    let hour = 4 // 4:00 am in GMT+0
    let minute = 0 // in GMT+0
    guard let timeZone = TimeZone(secondsFromGMT: 0) else { return }
    var calendar = Calendar(identifier: .gregorian) // Should be the calendar that is used by your server
    calendar.timeZone = timeZone
    let date = Date()
    let dateComponents = calendar.dateComponents(Set(arrayLiteral: Calendar.Component.weekday,
                                                     Calendar.Component.hour,
                                                     Calendar.Component.minute), from: date)
    var dateComponentsDiff = DateComponents()
    dateComponentsDiff.day = weekday - dateComponents.weekday!
    dateComponentsDiff.hour = hour - dateComponents.hour!
    dateComponentsDiff.minute = minute - dateComponents.minute!
    guard let arbitraryDate = calendar.date(byAdding: dateComponentsDiff, to: date),
          let pstTimeZone = TimeZone(abbreviation: "PST") else { return }
    let pstDateComponents = calendar.dateComponents(in: pstTimeZone, from: arbitraryDate)
    print("WEEK DAY: \(pstDateComponents.weekday!)\nTIME: \(pstDateComponents.hour!):\(pstDateComponents.minute!)")
    

    Output:

    WEEK DAY: 1
    TIME: 20:0