如何在Swift代码中转换天气API的日出日落时间数据?
解决Swift中Unix时间戳转时分秒格式的问题
没问题,我来帮你把天气API返回的Unix时间戳转成友好的时分秒格式显示。你的代码现在直接输出了原始时间戳,我们只需要加两步:把时间戳转成Date对象,再用DateFormatter格式化目标格式。
修改后的完整代码
if let sysDictionary = jsonObj?.value(forKey: "sys") as? NSDictionary { // 安全解析Unix时间戳(注意API返回的是秒级时间戳) if let sunriseTimestamp = sysDictionary.value(forKey: "sunrise") as? TimeInterval { // 1. 将秒级时间戳转为Date对象 let sunriseDate = Date(timeIntervalSince1970: sunriseTimestamp) // 2. 配置日期格式化器 let dateFormatter = DateFormatter() dateFormatter.locale = Locale.current // 使用当前设备的区域设置 dateFormatter.timeZone = TimeZone.current // 使用当前设备时区,也可以根据API的country设置,比如TimeZone(identifier: "America/Toronto") dateFormatter.dateFormat = "HH:mm:ss" // 时分秒格式,你也可以改成"h:mm a"来显示12小时制带AM/PM // 3. 格式化日期为字符串 let sunriseString = dateFormatter.string(from: sunriseDate) DispatchQueue.main.async { self.sunriseLabel.text = "Sunrise: \(sunriseString)" } } }
关键细节说明
- 时间戳类型转换:API返回的
sunrise是秒级Unix时间戳,所以直接转成TimeInterval(本质是Double)就能用来初始化Date。 - DateFormatter配置:
- 一定要设置
locale和timeZone,否则可能会出现格式化结果不符合预期的情况(比如默认用UTC时区)。 dateFormat可以根据需求调整:比如"h:mm a"会显示类似6:09 AM的12小时制格式,"HH:mm"则是24小时制的时分格式。
- 一定要设置
- 安全解析:用
as? TimeInterval替代直接强制解包,避免因为API返回数据格式异常导致崩溃。
如果需要同时处理日落时间,逻辑是完全一样的,只需要把sunrise换成sunset即可。
内容的提问来源于stack exchange,提问作者Rich J
相关产品推荐
相关产品推荐

