java 将 Joda LocalDateTime 转换为 Unix 时间戳

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32906265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 20:57:21  来源:igfitidea点击:

Convert Joda LocalDateTime to Unix timestamp

javajodatimeunix-timestamp

提问by Denis Kulagin

How do I convert a org.joda.time.LocalDateTimeto an Unix timestamp, given that local time is in UTC timezone?

org.joda.time.LocalDateTime鉴于本地时间在 UTC 时区,如何将 a 转换为 Unix 时间戳?

Example:

例子:

new LocalDateTime(2015, 10, 02, 11, 31, 40)> 1443785500.

new LocalDateTime(2015, 10, 02, 11, 31, 40)> 1443785500.

回答by Jon Skeet

Given that you want the Unix timestamp "the given LocalDateTime, in UTC" the simplest approach is just to convert it to a DateTimeby specifying the DateTimeZonefor UTC, and convert that:

鉴于您想要 Unix 时间戳“给定LocalDateTime的 UTC”,最简单的方法就是DateTime通过指定DateTimeZonefor UTC将其转换为 a ,然后将其转换为:

LocalDateTime local = new LocalDateTime(2015, 10, 02, 11, 31, 40);
DateTime utc = local.toDateTime(DateTimeZone.UTC);
long secondsSinceEpoch = utc.getMillis() / 1000;

Note the use of seconds here as a Unix timestamp - other APIs (e.g. java.util.Date) may expect milliseconds since the Unix epoch.

请注意这里使用秒作为 Unix 时间戳 - 其他 API(例如java.util.Date)可能期望自 Unix 纪元以来的毫秒数。