java - 如何将长本地时间戳转换为字符串 UTC 时间戳
问题描述
这个问题很接近我的,但是我发现答案不适合我。我的时间戳很长。
ts = 1362156863140L
因为它很长,我认为它是时区天真的时间戳,对吗?这是科隆当地时间的时间戳 - UTC+0200 (CET)。因此,当我将其转换为字符串时区感知时间戳时,我想获得:
2013-03-01T14:54:23.140Z
或者
2013-03-01T16:54:23.140+02:00
我在问题开始时使用答案中的解决方案:
Instant.ofEpochMilli(timestamp).atOffset(ZoneOffset.of("+2"));
返回:
2013-03-01T18:54:23.140+02:00
另一个时区:
Instant.ofEpochMilli(timestamp).atOffset(ZoneOffset.of("Z"));
返回:
2013-03-01T16:54:23.140Z
所以这些方法并没有真正改变时区,它们只是改变了时间戳的表示。我还尝试了另一种方法:
OffsetDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.of("UTC"));
但结果完全一样。这个解决方案很有用,但原始方法:
int offset = TimeZone.getTimeZone("Europe/Amsterdam").getRawOffset();
long newTime = timestamp - offset;
不考虑夏季/冬季时间。建议的答案使用 JDK8 已过时的 Calendar 类。有效且足够明显的是:
OffsetDateTime.ofInstant(Instant.ofEpochMilli(Timestamp), ZoneId.of("UTC")).minusSeconds(7200);
但这显然不是正确的方法,那么我该如何使用时区来做到这一点?
解决方案
我想时间戳在UTC
,您需要将时间戳更改为CET
. 看看withZoneSameInstant()
方法,可能会有帮助。
long timeStamp = 1362156863140L;
ZoneId sourceZone = ZoneId.of("UTC");
ZoneId targetZone = ZoneId.of("CET");
String s = ZonedDateTime.ofInstant(Instant.ofEpochMilli(timeStamp), sourceZone)
.withZoneSameLocal(targetZone)
.toString();
System.out.println(s);
推荐阅读
- javascript - 编写插入变量的 HTML 文件?
- sql - 在 Haskell 中可以调用带有表类型参数的存储过程吗?
- ruby - bash_profile 环境变量问题:ruby 版本将被初始化
- python - 如何在不使用 display.specshow 的情况下缩放 librosa 频谱图的频率轴?
- sql - 获取自动化错误 Excel VBA 尝试更新 SQL Db
- java - (仅限 Netbeans)找不到适合 jdbc:mysql://localhost 的驱动程序
- php - 如何在循环外使用从嵌套 foreach 循环生成的值?
- python - 尝试,捕捉,除了在数据框中
- reactjs - 为什么我们在 {} 中导入/要求一些对象以小写字母和一些大写字母反应?
- rust - 在 Rust 的一行中定义和分配一个二维数组 a