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

Java中如何将日期转换为带+0000的UTC格式?

解决方案

方法一:修改现有SimpleDateFormat代码(旧API)

问题出在SimpleDateFormat默认使用本地时区进行格式化,导致输出的时区偏移是你当前所在时区(比如+0300)。要强制输出UTC时区(+0000),只需给格式化器指定UTC时区即可:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class DateConversion {
    public static void main(String[] args) {
        String oldDate = "20230523154325";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        // 解析时指定UTC时区,避免本地时区干扰解析结果
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date newDateFormat = null;

        try {
            newDateFormat = sdf.parse(oldDate);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        // 关键:设置格式化器为UTC时区
        sdf1.setTimeZone(TimeZone.getTimeZone("UTC"));
        System.out.println("The date is " + sdf1.format(newDateFormat));
    }
}

说明:

  • 给解析用的sdf设置UTC时区,确保解析出的Date对象准确对应UTC时间的"2023-05-23 15:43:25"。
  • 给格式化用的sdf1设置UTC时区,格式化后会输出+0000的时区偏移。

方法二:使用Java 8+ 新日期API(推荐)

SimpleDateFormat是线程不安全的,Java 8及以后推荐使用java.time包下的日期API,更可靠易用:

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;

public class DateConversion {
    public static void main(String[] args) {
        String oldDate = "20230523154325";
        // 解析字符串为LocalDateTime
        LocalDateTime localDateTime = LocalDateTime.parse(oldDate, DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        // 转换为UTC时区的OffsetDateTime
        OffsetDateTime utcDateTime = localDateTime.atOffset(java.time.ZoneOffset.UTC);
        // 格式化目标格式
        String formattedDate = utcDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ"));
        System.out.println("The date is " + formattedDate);
    }
}

说明:

  • LocalDateTime解析不带时区的字符串,通过atOffset(ZoneOffset.UTC)转为UTC时区的偏移日期时间。
  • DateTimeFormatter是线程安全的,适合多线程环境,代码逻辑更简洁清晰。

两种方法都能输出你需要的2023-05-23T15:43:25+0000格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 10:17:19