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

如何在Java中获取2022-10-03T19:45:47.844Z格式的日期时间

Java获取当前UTC时间并格式化为指定格式

你需要的2022-10-03T19:45:47.844Z是ISO 8601标准的UTC时间格式,下面分两种方式实现,优先推荐Java 8+的新日期API(更安全、易用):

一、使用Java 8+新日期API(推荐)

方法1:用Instant直接获取UTC时间

Instant类本身就代表UTC时间,配合DateTimeFormatter.ISO_INSTANT可以直接得到目标格式:

import java.time.Instant;
import java.time.format.DateTimeFormatter;

public class DateTimeDemo {
    public static void main(String[] args) {
        // 获取当前UTC时间
        Instant currentUtcTime = Instant.now();
        // 格式化为目标格式
        String formattedTime = DateTimeFormatter.ISO_INSTANT.format(currentUtcTime);
        System.out.println(formattedTime); // 输出类似:2024-05-20T12:34:56.789Z
    }
}

解释:Instant.now()直接获取当前UTC时刻,ISO_INSTANT是内置的格式化器,正好匹配你要的格式,不需要手动写格式串。

方法2:用ZonedDateTime转UTC时区

如果需要从本地时间转UTC,或者更灵活控制时区,可以用ZonedDateTime:

import java.time.ZonedDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class DateTimeDemo {
    public static void main(String[] args) {
        // 获取当前时间并转为UTC时区
        ZonedDateTime utcDateTime = ZonedDateTime.now(ZoneOffset.UTC);
        // 方式1:用内置格式化器
        String formatted1 = utcDateTime.format(DateTimeFormatter.ISO_INSTANT);
        // 方式2:自定义格式串(和目标格式完全匹配)
        String formatted2 = utcDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX"));
        
        System.out.println(formatted1);
        System.out.println(formatted2); // 两种方式输出一致
    }
}

解释:ZoneOffset.UTC指定时区为UTC,自定义格式串中的X会输出UTC对应的Z符号。

二、使用旧API(SimpleDateFormat,不推荐)

虽然SimpleDateFormat是旧API(线程不安全,易出问题),但还是给你实现方式:

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

public class OldDateTimeDemo {
    public static void main(String[] args) {
        // 创建格式化器,注意Z要加单引号转义为文字
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        // 设置时区为UTC,否则会用本地时区
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        // 格式化当前时间
        String formattedTime = sdf.format(new Date());
        System.out.println(formattedTime);
    }
}

注意:如果不加单引号转义Z,SimpleDateFormat会把它解析为时区偏移(比如输出+0000),所以必须用'Z'表示文字Z。

给初学者的建议

  • 尽量使用Java 8及以上版本的java.time包下的类(Instant、ZonedDateTime、DateTimeFormatter等),它们线程安全,API设计更清晰,避免旧API的诸多问题。
  • 目标格式是标准的ISO 8601 UTC格式,用内置的ISO_INSTANT格式化器比手动写格式串更可靠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 21:45:35