将UTC日期转换为毫秒

问题描述 投票:8回答:6

我对当前UTC时间以毫秒为单位不感兴趣,也不需要弄乱时区。我的原始日期已经存储为UTC时间戳。

我在UTC时间“ 2012-06-14 05:01:25”中存储了一个日期。我对日期时间不感兴趣,但对日期部分感兴趣。因此,在用Java检索日期后,不包括小时,分钟和秒,我留下的是“ 2012-06-14”。

如何将其转换为UTC毫秒?

java time utc milliseconds
6个回答
12
投票

编辑:我错过了“忽略一天中的时间”部分。它现在存在,但是快要结束了...

最简单的方法可能是使用SimpleDateFormat,并已适当设置了时区:

SimpleDateFormat

((设置时区在这里很重要,否则它将解释该值位于local时区中。)

或者,如果您做的事情不那么琐碎,请使用SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US); format.setTimeZone(TimeZone.getTimeZone("UTC")); Date date = format.parse(text); long millis = date.getTime(); ,它是更好的日期/时间API。特别是Joda Time 不是线程安全的,而SimpleDateFormat是:

DateTimeFormatter

[到目前为止,我们已经解析了整个Caboodle。忽略日期部分的最简单方法是将其四舍五入-毕竟,Java没有观察到leap秒,因此我们可以截断它:

DateTimeFormatter

这将“朝1970年舍入”,因此,如果您将日期设为[[before 1970年,它将舍入到一天的end,但我怀疑这不太可能成为问题。

对于Joda Time版本,您可以改用它:

// This can be reused freely across threads after construction. DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss") .withLocale(Locale.US) .withZoneUTC(); // Option 1 DateTime datetime = formatter.parseDateTime(text); long millis = dateTime.getMillis(); // Option 2, more direct, but harder to diagnose errors long millis = formatter.parseMillis(text);

我个人会[[not
”只接受一个子字符串。即使您实际上对

preserving时/分/秒不感兴趣,我认为解析您得到的信息并丢弃信息也是适当的。除了其他方面,它还会使您的代码因数据错误而相应地失败,例如long millisPerDay = 24L * 60L * 60L * 1000L; // Or use TimeUnit long dayMillis = (millis / millisPerDay) * millisPerDay;

DateTime dateTime = formatter.parseDateTime(text); long millis = dateTime.toLocalDate().getLocalMillis();
指出在提供数据的任何方面都存在问题,发现这一点而不是仅仅因为前10个字符都可以就盲目地继续是很好的。

2
投票

1
投票

0
投票

0
投票

-1
投票
© www.soinside.com 2019 - 2024. All rights reserved.