简体   繁体   English

快速-获取具有不同时区的当前日期以在时间之间进行比较

[英]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. 我需要获取一个NSDate类型的Date,而不是一个String,它包含特定时区的当前时间,以便以后进行比较以查看时间是否在一个范围内。

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. 我现在是美国东部标准时间(EST)时区,现在是11:30 pm,所以我看到一家商店的时间表是在11点关门,但是该商店是在PST,这意味着现在该区域的时间是晚上10点,并且仍然开放。 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. 但是,当我转换包含正确设置时区的时间的String并将其解析回Date类型时,它只是忽略timeZone并显示不同的时间。 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(); 假设这是我得到的信息:Now = Date(); OpenTime = 2018-04-27 11:00:00 +0000; OpenTime = 2018-04-27 11:00:00 +0000; CloseTime = 2018-04-28 03:00:00 +0000; 收盘时间= 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? StoreTimeZone =“ EST”如果我在与商店时区不同的地方,是否容易获得商店是否营业的信息? 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. 我已经具有要比较的功能,因为时间介于OpenTime和CloseTime之间,我只需要在存储中传递正确的时间即可获取当前时间是否为打开状态。

Thanks in advance. 提前致谢。

Here is my solution. 这是我的解决方案。 I have added a timezone to the JSON in a convenient place; 我在方便的地方为JSON添加了时区; 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 商店是:开

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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