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

询问ISO 8601日期时间格式及当前时间转该格式的实现方法

ISO 8601 日期时间格式解析与转换

格式类型

这两个都是ISO 8601标准的日期时间表示格式:

  • 2022-08-12T01:47:24.856316:包含年-月-日、时间分隔符T、时分秒,以及微秒级精度的小数部分,未指定时区,通常需要结合上下文确定是本地时间还是其他时区。
  • 2022-09-15T08:32:38.490Z:同样遵循ISO 8601,末尾的Z是UTC时区的标记,代表协调世界时,精度到毫秒。

转换为该格式的实现

以下是几种主流编程语言的实现方式:

Python

  • 生成带微秒、无时区的格式:
from datetime import datetime

current = datetime.now()
iso_str = current.isoformat()
print(iso_str)  # 示例输出:2024-05-20T15:40:22.789012
  • 生成带UTC时区、毫秒精度的格式:
from datetime import datetime, timezone

current_utc = datetime.now(timezone.utc)
iso_utc_str = current_utc.isoformat(timespec='milliseconds').replace('+00:00', 'Z')
print(iso_utc_str)  # 示例输出:2024-05-20T07:40:22.789Z

JavaScript

  • 生成带微秒、无时区的格式:
const now = new Date();
// 拆分默认ISO字符串(到毫秒),拼接微秒部分
const [datePart, msPart] = now.toISOString().split('.');
const microseconds = Math.floor(now.getMilliseconds() * 1000);
const isoNoTz = `${datePart}.${msPart.slice(0,3)}${microseconds.toString().padStart(3, '0')}`;
console.log(isoNoTz); // 示例输出:2024-05-20T15:40:22.789012
  • 生成带UTC时区、毫秒精度的格式:
const now = new Date();
console.log(now.toISOString()); // 示例输出:2024-05-20T07:40:22.789Z

Java

  • 生成带微秒、无时区的格式:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class IsoFormatExample {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS");
        String isoStr = now.format(formatter);
        System.out.println(isoStr); // 示例输出:2024-05-20T15:40:22.789012
    }
}
  • 生成带UTC时区、毫秒精度的格式:
import java.time.Instant;

public class IsoUtcExample {
    public static void main(String[] args) {
        Instant now = Instant.now();
        System.out.println(now.toString()); // 示例输出:2024-05-20T07:40:22.789Z
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 18:40:31