jodatime - Joda-time:如何将本地时间转换为 UTC,然后仅使用毫秒转换为另一个本地时间?
问题描述
就像 LotR 一样,Java 中的 TimeZone 转换是一个传奇。我的要求很简单。问题在于使用毫秒来创建 DateTime 对象。
我需要能够以毫秒为单位获取本地时间,然后以毫秒为单位将其转换为 UTC,然后将其转换回相同的本地时间,全部使用毫秒。我对 JodaTime 有一些了解,但是在下面的示例中将 UTC 毫秒时间转换回原始本地时间一直是个问题。这是我起床的地方:
public static final TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
public static final String DATETIME_REVERSE = "yyyy-MM-dd 'T' HH:mm:ss";
private void thereAndBackAgain() {
long nowTimeNumber = 1585715400000L;
DateTime nowDt = new DateTime(nowTimeNumber);
DateTimeFormatter formatter = DateTimeFormat.forPattern(DATETIME_REVERSE);
// Get local time
Timber.e(" -- 1. Local Time :" + nowDt.getMillis() + " -> " + formatter.print(nowDt));
// Convert Local to UTC
DateTime utcTime = nowDt.withZone(DateTimeZone.UTC); // Convert to UTC.
String utcTimeStr = formatter.print(utcTime);
long utcOfLocalInMilli = formatter.parseDateTime(utcTimeStr).withZone(DateTimeZone.UTC).getMillis();
Timber.e(" -- 2. UTC Time :" + utcOfLocalInMilli + " -> " + formatter.print(utcTime));
// Convert UTC back to Local
DateTime utc2 = new DateTime(utcOfLocalInMilli, DateTimeZone.UTC);
DateTimeFormatter formatter2 = DateTimeFormat.forPattern(DATETIME_REVERSE);
String utc2str = formatter2.print(utc2);
long localOfUtcInMillis = formatter2.parseDateTime(utc2str).withZone(DateTimeZone.getDefault()).getMillis();
Timber.e(" -- 3. Local Time :" + localOfUtcInMillis + " -> " + utc2str);
}
输出是:
-- 1. Local Time :1585715400000 -> 2020-04-01 T 15:30:00
-- 2. UTC Time :1585675800000 -> 2020-04-01 T 04:30:00
-- 3. Local Time :1585636200000 -> 2020-03-31 T 17:30:00
我遇到的问题是,当我创建 utc2 时,JodaTime 仍然假定毫秒值是本地时区,即使我使用 UTC 时区声明它也是如此。但是我很可能误解了这个构造函数的用法。
基本上,我希望能够从任何时区获取时间,以毫秒为单位转换为 UTC,然后将其转换回任何其他时区。数据库键需要毫秒值。此示例仅使用本地时间,然后转换回相同的时间,但理想情况下,这旨在从一个时区转换为另一个时区,同时使用单个毫秒时间值,然后针对时区进行调整。
解决方案
推荐阅读
- java - 仅将唯一的属性记录保存到数据库的良好做法
- python - 烧瓶:send_from_directory
- c - 我自己的带指针的 strcat 函数无法正常工作
- java - 如何使用Hibernate或JPA在不删除映射表中先前数据的情况下建立多对多关系
- scala - Gatling 中的可选 queryParam
- kivy - kivy : kvlan 注册失败
- javascript - 动态解析表行的数据
- lua - Corona SDK 分布和对象大小
- docker - 如何将 OpenShift 上的 KSQLDB 集群连接到本地 Kerberized Kafka 集群
- unit-testing - 如何测试具有 Db Context 和 Logger 的 Asp.Net Core 控制器?