Java convert UTC timestamp to local DateTime(Java 将 UTC 时间戳转换为本地 DateTime)
问题描述
我知道已经有几十篇关于将 UTC 时间/日期转换为/从本地时间的回复帖子,但没有帮助我弄清楚我的问题是什么.我的问题是:通过拥有 UTC 时间戳,我如何获得本地 DateTime?这就是我现在所拥有的,但这只是将时间戳转换为 DateTime 格式.
I know there are dozens of answered posts about converting UTC Time/Date To/From local time already but non helped me to figure out what my problem is. My question is: By having UTC timestamp, how can i get local DateTime? This is what I have right now but this just convert the timestamp to DateTime format.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getDefault());
sdf.format(new Date(timestamp * 1000));
已我将 UTC 时间戳保存在云端,以便每台设备(Android/iOS)都可以查询并转换到它的时区.
Edited: I'm saving the UTC timestamp on the cloud so every device (Android/iOS) can query and convert to it's time zone.
推荐答案
试试这个对我有用
public String getDateCurrentTimeZone(long timestamp) {
try{
Calendar calendar = Calendar.getInstance();
TimeZone tz = TimeZone.getDefault();
calendar.setTimeInMillis(timestamp * 1000);
calendar.add(Calendar.MILLISECOND, tz.getOffset(calendar.getTimeInMillis()));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date currenTimeZone = (Date) calendar.getTime();
return sdf.format(currenTimeZone);
}catch (Exception e) {
}
return "";
}
这篇关于Java 将 UTC 时间戳转换为本地 DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 将 UTC 时间戳转换为本地 DateTime


- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01