将毫秒转换为UTC时间戳

5

我试图将毫秒转换为带有UTC时区的时间戳,但它并没有按照预期工作,因为它转换为了我的本地时间。

我尝试过以下方法。在调试代码时,我发现当执行以下代码时:new DateTime(eventDate)它正常工作,因为它的值是10:34:18.721,但稍后的new Timestamp()会将其更改为本地时间。

long eventDate = 1566297258721L;
DateTimeZone.setDefault(DateTimeZone.UTC);
Timestamp timestamp = new Timestamp(new DateTime(eventDate).getMillis());

我希望输出为:2019-08-20 10:34:18.721,但实际输出是:2019-08-20 12:34:18.721

感谢所有的回复!我已经通过另一种方式解决了这个问题。我在数据库中将该字段定义为“long”数据类型,因为它是自Unix纪元以来的毫秒数,所以每当我想在不同的时区使用它时,我可以格式化这个长整型值。 - kamboj
这是一个糟糕的解决方案,很抱歉。在进行更改后,您的数据库值变得难以阅读,并且在即席查询中没有太多价值。您使用哪个数据库引擎?Java 版本?任何 JPA 实现或类似的东西吗?PS:Timestamp 没有时区,但该类设计得很差且已过时。 - Ole V.V.
3个回答

4

您可以使用Java 8及更高版本中的java.time包

ZonedDateTime zonedDateTime = Instant.ofEpochMilli(1566817891743L).atZone(ZoneOffset.UTC);

1

我不理解为什么你要创建一个新的DateTime,然后从那里获取毫秒数,如果一开始你已经有了毫秒数。 也许我误解了你的问题。毫秒与时区无关。时区用于比较两个不同地方的同一时刻并获取相应的日期。以下是我的解决方案

如果你想从毫秒数获得时间戳:

long eventDate = 1566297258721L;
Timestamp time=new Timestamp(eventDate);
System.out.println(time);

结果将是2019-08-20 10:34:18.721,也是所需的SQL格式。

如果您想将一个时刻从一个时区转换到另一个时区:

您将在您当前的时区中获得该时刻,并将其转换为另一个时区,以便查看例如在其他国家的时间。

long eventDate = 1566297258721L;
Calendar calendar = Calendar.getInstance();
calendar.setTime(eventDate);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
dateFormat.format(calendar.getTime());

我希望这些代码片段对你有所帮助。愉快编程!

0
你可以尝试以下代码:
long eventDate = 1566297258721L;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z", Locale.US);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String stringDate = simpleDateFormat.format(new Date(eventDate));
System.out.println(stringDate);

它给我以下输出。

2019年08月20日10:34:18 UTC


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接