不同时区的相同倒计时 - Swift

Same Countdown in different TimeZone - Swift

我已经创建了一个在 CEST 时区运行良好的倒计时,但我希望它能在所有时区不同的国家/地区显示相同的正确剩余时间。

知道如何操作代码吗?

 // here we set the current date
    let date = NSDate()
    let calendar = Calendar.current

    let components = calendar.dateComponents([.hour, .minute, .month, .year, .day], from: date as Date)

    let currentDate = calendar.date(from: components)

    let userCalendar = Calendar.current

    // here we set the due date. When the timer is supposed to finish
    let competitionDate = NSDateComponents()
    competitionDate.year = year
    competitionDate.month = month
    competitionDate.day = day
    competitionDate.hour = hour
    competitionDate.minute = minute
    let competitionDay = userCalendar.date(from: competitionDate as DateComponents)!

    //here we change the seconds to hours,minutes and days
    let competitionDayDifference = calendar.dateComponents([.day, .hour, .minute], from: currentDate!, to: competitionDay)


    //finally, here we set the variable to our remaining time
    let daysLeft = competitionDayDifference.day
    let hoursLeft = competitionDayDifference.hour
    let minutesLeft = competitionDayDifference.minute

    print("day:", daysLeft ?? "N/A", "hour:", hoursLeft ?? "N/A", "minute:", minutesLeft ?? "N/A")

您当前的代码不起作用,因为比赛日不是由时间点(自 1970 年以来的 x 秒)表示,而是作为 本地日期时间(年、月、日、小时、分钟等)代替。

要将比赛日期表示为时间点,您需要将其与您未提供的时区相关联。您可以向用于从日期组件中获取 DateCalendar 提供一个:

var userCalendar = Calendar.current
userCalendar.timeZone = TimeZone(identifier: "...")!

然后无论设备处于哪个时区,比赛日期都会转换为相同的时间点。

或者,设置 competitionDate.timeZone:

competitionDate.timeZone = TimeZone(identifier: "...")!