You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将带时区的Joda DateTime转换为同时间值的UTC DateTime?

解决方法

你需要创建一个新的DateTime实例,保留原时间的年、月、日、时分秒毫秒值,但将时区设置为UTC,而非执行时区转换。以下是两种可行方案:

方案一:提取字段重新构造

直接提取原DateTime的时间字段,用UTC时区重新构建实例:

DateTime date = new DateTime("2022-10-30T00:00:00.000+11:00");
DateTime utcTarget = new DateTime(
    date.getYear(),
    date.getMonthOfYear(),
    date.getDayOfMonth(),
    date.getHourOfDay(),
    date.getMinuteOfHour(),
    date.getSecondOfMinute(),
    date.getMillisOfSecond(),
    DateTimeZone.UTC
);
// 此时utcTarget.getMillis()返回UTC时区2022-10-30 00:00:00对应的毫秒数

方案二:使用withZoneRetainFields方法

Joda-Time提供的withZoneRetainFields方法可直接保留原时间字段值,仅切换时区:

DateTime date = new DateTime("2022-10-30T00:00:00.000+11:00");
DateTime utcTarget = date.withZoneRetainFields(DateTimeZone.UTC);
// 调用utcTarget.getMillis()即可获取目标毫秒数

关键区别说明

  • withZone(DateTimeZone.UTC)会执行时区转换,将原时间转换为UTC对应的实际时间(也就是你当前得到的前一天时间);
  • withZoneRetainFields(DateTimeZone.UTC)是保留字段值切换时区,直接把原时间的年月日时分秒映射到UTC时区,完全匹配你的需求。

内容的提问来源于stack exchange,提问作者jjj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 20:10:45