简体   繁体   中英

Swift- Get current date with different timezones to compare between times

I've been looking for this but couldnt found a solution that corresponds correctly with my needs. I need to get a Date of type NSDate, not a String, which includes the current time of a specific timezone to later compare it to see if the time is between a range.

For example I need to see if a store is open. I am at EST timezone and it's 11:30 pm so I see the schedule of a store that closes at 11 but the store is at PST which means that now it's 10pm in that zone and stills open. So I need to change my timezone to the store timezone to show a flag if it is open or closed right now.

This is an example of what I tried:

guard let tz = model?.timeZone else {return "EST"};    
let tz = TimeZone.init(abbreviation: timeZone);
df.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ";
let dateString = df.string(from:Date()); //time is correct
let date = df.date(from: dateString); //ignore timeZone and transform to a different date.

But when I convert the String that do contains the time with the timezone set correctly and parse it back to Date type it just ignore the timeZone and displays a different time. I think I will have to do something like get the difference between times and add to the current time but Im not really sure of how to get that done. Because this is what I've been trying to do too:

let localTimeZoneOffset = myTimeZone.secondsFromGMT(for: Date());
let currentTime = Date().addingTimeInterval(TimeInterval(- 
localTimeZoneOffset));

Still I could be at any area and I want to see if a store of another area is open hagin different timezones for both, the current time of the device and open-closed time of the store. My location could be anywhere and the store I pick too, so I think I would need to get the difference of both times or something like that

Let's supposed this is the info I got: Now = Date(); OpenTime = 2018-04-27 11:00:00 +0000; CloseTime = 2018-04-28 03:00:00 +0000; StoreTimeZone = "EST" With this info is it easy to get if the store is open or not if I am in a place with different timezone from the store? I already have the functions to compare is time is between the OpenTime and the CloseTime I just need to pass the correct time in the store to get if it is open or not right now.

Thanks in advance.

Here is my solution. I have added a timezone to the JSON in a convenient place; you would need to adapt to allow for the location of the timezone in your data.

struct Schedule: Codable {
    var timezone: String
    var storeHours: [DayHours]
}

struct DayHours: Codable {
    var hours: String
    var day: String
    var date: String
}


struct OpeningHours {
    let day: String
    let openTime: Date
    let closeTime: Date

    func isOpen(on date: Date) -> Bool {
        return date >= openTime && date < closeTime
    }
}

struct StoreSchedule {
    let openingHours:[OpeningHours]
    let timezone: TimeZone

    init?(_ schedule: Schedule) {
        guard let timezone = TimeZone(abbreviation:schedule.timezone) else {
            return nil
        }

        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd hh:mm a"
        dateFormatter.timeZone = timezone
        self.timezone = timezone
        var openingHours = [OpeningHours]()
        for dayHours in schedule.storeHours {
            let components = dayHours.hours.components(separatedBy: "-")
            guard components.count == 2 else {
                return nil
            }
            let opening = components[0]
            let closing = components[1]
            guard let openTime = dateFormatter.date(from: "\(dayHours.date) \(opening)"),
                let closeTime = dateFormatter.date(from: "\(dayHours.date) \(closing)") else {
                    return nil
            }
            openingHours.append(OpeningHours(day: dayHours.day, openTime: openTime, closeTime: closeTime))
        }

        self.openingHours = openingHours
    }

    func isOpen(on date: Date) -> Bool{
        for openings in openingHours {
            if openings.isOpen(on: date) {
                return true
            }
        }
        return false
    }
}

let json = """
{
"timezone": "PST",
"storeHours": [{
"hours": "7:00 AM - 11:00 PM",
"day": "Friday",
"date": "2018-04-27"
}, {
"hours": "7:00 AM - 11:00 PM",
"day": "Saturday",
"date": "2018-04-28"
}, {
"hours": "7:00 AM - 11:00 PM",
"day": "Sunday",
"date": "2018-04-29"
}, {
"hours": "7:00 AM - 11:00 PM",
"day": "Monday",
"date": "2018-04-30"
}, {
"hours": "7:00 AM - 11:00 PM",
"day": "Tuesday",
"date": "2018-05-01"
}, {
"hours": "7:00 AM - 11:00 PM",
"day": "Wednesday",
"date": "2018-05-02"
}, {
"hours": "7:00 AM - 11:00 PM",
"day": "Thursday",
"date": "2018-05-03"
}]
}
"""

let schedule = try! JSONDecoder().decode(Schedule.self, from: json.data(using: .utf8)!)

if let storeSchedule = StoreSchedule(schedule) {
    //  print(storeSchedule)
    let openClosed = storeSchedule.isOpen(on: Date()) ? "Open":"Closed"
    print("Store is: \(openClosed)")
} else {
    print("Unable to create schedule")
}

Store is: Open

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM