不同时区的相同倒计时 - Swift
创始人
2025-01-09 16:32:28
0

下面是一个使用 Swift 编写的示例代码,用于在不同的时区显示相同的倒计时。

import Foundation

func countdownTimer(timeZone: TimeZone) {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    dateFormatter.timeZone = timeZone
    
    let targetDate = dateFormatter.date(from: "2022-12-31 23:59:59")!
    
    let timer = Timer(fire: Date(), interval: 1, repeats: true) { timer in
        let currentDate = Date()
        let remainingTime = Calendar.current.dateComponents([.day, .hour, .minute, .second], from: currentDate, to: targetDate)
        
        print("\(timeZone.identifier): \(remainingTime.day ?? 0) days, \(remainingTime.hour ?? 0) hours, \(remainingTime.minute ?? 0) minutes, \(remainingTime.second ?? 0) seconds")
    }
    RunLoop.current.add(timer, forMode: .common)
}

countdownTimer(timeZone: TimeZone(identifier: "America/New_York")!) // 美国东部时间
countdownTimer(timeZone: TimeZone(identifier: "Asia/Tokyo")!) // 东京时间
countdownTimer(timeZone: TimeZone(identifier: "Europe/London")!) // 伦敦时间

这个示例代码中,我们首先定义了一个 countdownTimer 函数,它接受一个 TimeZone 参数。在函数内部,我们使用 DateFormatter 来设置日期格式和时区。然后,我们将目标日期解析为一个 Date 对象。

接下来,我们创建了一个定时器 timer,它会每秒触发一次。在定时器的回调闭包中,我们计算当前日期与目标日期之间的剩余时间,并使用 CalendardateComponents 方法来获取剩余时间的天、小时、分钟和秒数。

最后,我们通过调用 countdownTimer 函数,并传入不同的时区来显示相同的倒计时。在示例代码中,我们使用了美国东部时间、东京时间和伦敦时间作为例子,你可以根据自己的需求选择其他的时区。

相关内容

热门资讯

透视辅助!cloudpoker... 透视辅助!cloudpoker开挂(透视)aapoker透视方法,教程模板(真实有挂)-哔哩哔哩1、...
wejoker辅助软件视频!德... wejoker辅助软件视频!德扑圈透视(透视)技巧-切实普及是真的挂;1、很好的工具软件,可以解锁游...
wpk辅助器是真的吗!wepo... wpk辅助器是真的吗!wepoker破解器(透视)app-本来推荐是有挂1)wpk辅助器是真的吗有没...
透视详细!wepoker透视脚... 透视详细!wepoker透视脚本(透视)hhpoker辅助靠谱吗,教程教材(确实有挂)-哔哩哔哩1、...
德州机器人代打脚本!wepok... 德州机器人代打脚本!wepoker辅助器激活码(透视)app-其实解谜存在有挂1)德州机器人代打脚本...
透视总结!hhpoker辅助软... 透视总结!hhpoker辅助软件下载(透视)pokerworld破解版下载,教程机巧(有挂秘籍)-哔...
黑侠破解wepoker!hhp... 黑侠破解wepoker!hhpoker俱乐部是干嘛的(透视)app-都是普及真的是有挂1、上手简单,...
透视分享!wpk真吗(透视)德... 透视分享!wpk真吗(透视)德州局怎么透视,教程法门(有挂功能)-哔哩哔哩1、德州局怎么透视公共底牌...
cloudpoker透视!we... cloudpoker透视!wepokerplus开挂(透视)挂-总是透视是有挂1、许多玩家不知道we...
透视解谜!德普之星透视免费(透... 透视解谜!德普之星透视免费(透视)wepoker怎么拿到好牌,教程阶段(有挂方式)-哔哩哔哩wepo...