Android中如何从OpenWeather API获取日期时间及星期并解析时间戳
如何把OpenWeather的Unix时间戳转换成日期、时间和星期?
嘿,这个问题我太熟悉啦!OpenWeather返回的1525974999这种长整数是Unix时间戳,也就是从1970年1月1日00:00:00 UTC开始累计的秒数。要把它转成你需要的日期、时间和星期,不同编程语言都有现成的工具,给你整理几个最常用的方案:
1. JavaScript(前端/Node.js场景)
JavaScript的Date对象直接支持Unix时间戳,但要注意:它默认接受毫秒级时间戳,所以需要把API返回的秒级戳乘以1000:
const timestamp = 1525974999; const date = new Date(timestamp * 1000); // 自定义格式化日期(比如"2018-05-11") const dateStr = date.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }); // 获取时间(比如"18:36:39") const timeStr = date.toLocaleTimeString('zh-CN'); // 获取中文星期(比如"星期五") const weekStr = date.toLocaleDateString('zh-CN', { weekday: 'long' }); console.log(`日期:${dateStr},时间:${timeStr},星期:${weekStr}`);
如果需要UTC时间,把上面的方法换成toLocaleDateString('en-US', { timeZone: 'UTC', ... })这类带时区参数的写法即可。
2. Python(后端/数据分析场景)
Python的datetime模块处理时间戳非常方便,支持直接转本地时间或UTC时间:
import datetime timestamp = 1525974999 # 转换为本地时间 local_dt = datetime.datetime.fromtimestamp(timestamp) # 转换为UTC时间 utc_dt = datetime.datetime.utcfromtimestamp(timestamp) # 格式化输出(英文格式) print("本地日期时间:", local_dt.strftime("%Y-%m-%d %H:%M:%S")) print("本地星期(英文):", local_dt.strftime("%A")) # 如果需要中文星期,可通过locale设置 import locale locale.setlocale(locale.LC_TIME, 'zh_CN.UTF-8') print("本地星期(中文):", local_dt.strftime("%A"))
3. Java(后端/Android场景)
Java 8+的java.time包是处理时间的最佳选择,能轻松处理时区转换:
import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; public class TimestampConverter { public static void main(String[] args) { long timestamp = 1525974999L; // 从秒级时间戳创建Instant Instant instant = Instant.ofEpochSecond(timestamp); // 转换为上海时区的时间(可替换为你需要的时区) ZonedDateTime localDt = instant.atZone(ZoneId.of("Asia/Shanghai")); // 定义格式化器 DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss"); DateTimeFormatter weekFormatter = DateTimeFormatter.ofPattern("EEEE"); // 输出结果 System.out.println("日期:" + localDt.format(dateFormatter)); System.out.println("时间:" + localDt.format(timeFormatter)); System.out.println("星期:" + localDt.format(weekFormatter)); } }
小提示
- OpenWeather返回的时间戳默认是UTC时区,转换时记得根据你的需求切换到本地时区或者保持UTC,避免时间偏差。
- 如果遇到毫秒级的时间戳(部分API会返回),就不需要乘以1000,直接传入对应方法即可。
内容的提问来源于stack exchange,提问作者Sohid Ullah
相关产品推荐
相关产品推荐

