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

Flutter/Dart如何将DateTime转换为yyyy-MM-dd'T'HH:mm:ss.SSS'Z'格式

遗漏关键点说明

你缺失的核心是时区偏移字段的处理:Dart内置的toIso8601String()默认仅输出不带时区标识的简化ISO8601格式,你看到的-0700这类后缀是UTC时区偏移量(格式为±HHmm),接口要求的Z是UTC+0时区的缩写,服务端因为无法识别你传入的缺失时区标识的时间字符串,所以返回415错误。


Dart 实现方案

Dart标准库没有内置时间格式化能力,需要借助官方维护的intl包实现:

  1. 首先在pubspec.yaml中添加依赖:
dependencies:
  intl: ^0.18.1 # 可替换为当前最新稳定版本
  1. 对应格式化代码:
import 'package:intl/intl.dart';

// 接口要求返回UTC时间带Z后缀时用这个方法
String formatUtcDateTime(DateTime dateTime) {
  final utcTime = dateTime.toUtc();
  return DateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").format(utcTime);
}

// 接口要求返回本地时间带时区偏移时用这个方法
String formatDateTimeWithOffset(DateTime dateTime) {
  final offset = dateTime.timeZoneOffset;
  String offsetSign = offset.isNegative ? '-' : '+';
  String offsetHours = offset.inHours.abs().toString().padLeft(2, '0');
  String offsetMinutes = (offset.inMinutes.abs() % 60).toString().padLeft(2, '0');
  String timeMainPart = DateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").format(dateTime);
  return "$timeMainPart$offsetSign$offsetHours$offsetMinutes";
}

输出示例:

  • formatUtcDateTime(DateTime.now()) → 2024-05-20T15:30:45.123Z
  • formatDateTimeWithOffset(DateTime.now()) → 2024-05-20T08:30:45.123-0700

Python 实现方案

Python标准库datetime可直接实现需求,无需额外依赖:

from datetime import datetime, timezone

# 输出带Z后缀的UTC时间
def get_utc_formatted_time():
    utc_now = datetime.now(timezone.utc)
    # %f输出6位微秒,截掉后3位得到3位毫秒
    return utc_now.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"

# 输出带本地时区偏移的时间
def get_offset_formatted_time():
    local_now = datetime.now().astimezone()
    time_main = local_now.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3]
    offset_part = local_now.strftime("%z")
    return time_main + offset_part

输出示例:

  • get_utc_formatted_time() → 2024-05-20T15:30:45.123Z
  • get_offset_formatted_time() → 2024-05-20T08:30:45.123-0700

额外校验点

如果修改时间格式后仍返回415错误,可同步检查请求头的Content-Type字段是否符合接口要求,比如JSON接口通常要求该字段值为application/json。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 06:45:06