如何使用 UTC 时区偏移格式化 DateTime?

Ton*_*ony 5 datetime dart flutter

这是什么类型的日期格式?

2020-03-26T00:57:08.000+08:00
Run Code Online (Sandbox Code Playgroud)

我正在使用DateFormat

 DateTime dateTime = DateTime.now();

 print(dateTime.toIso8601String());
 print(dateTime.toLocal());
 print(dateTime.toUtc());
Run Code Online (Sandbox Code Playgroud)

输出

I/flutter (20667): 2020-03-26T01:34:20.826589
I/flutter (20667): 2020-03-26 01:34:20.826589
I/flutter (20667): 2020-03-25 17:34:20.826589Z
Run Code Online (Sandbox Code Playgroud)

我想要一个像我显示的第一个输出一样的日期格式,后面有+08:00。我应该使用哪个?

Mid*_* MP 7

目前还没有直接的方法来获取这种日期格式。有一个解决方法。

  • 添加国际
  • 使用将其导入到您的文件中import 'package:intl/intl.dart';
  • 编写以下代码:
var dateTime = DateTime.now();
var val      = DateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").format(dateTime);
var offset   = dateTime.timeZoneOffset;
var hours    = offset.inHours > 0 ? offset.inHours : 1; // For fixing divide by 0

if (!offset.isNegative) {
  val = val +
      "+" +
      offset.inHours.toString().padLeft(2, '0') +
      ":" +
      (offset.inMinutes % (hours * 60)).toString().padLeft(2, '0');
} else {
  val = val +
      "-" +
      (-offset.inHours).toString().padLeft(2, '0') +
      ":" +
      (offset.inMinutes % (hours * 60)).toString().padLeft(2, '0');
}
print(val);
Run Code Online (Sandbox Code Playgroud)


tfm*_*gue 6


这是什么日期格式?
“2020-03-26T00:57:08.000+08:00”

此日期时间格式遵循 RFC 3339 标准,更普遍的是 ISO 8601 标准。字母“T”被称为时间指示符。“+08:00”被称为 UTC 时区偏移量。


我想要一个日期格式 [...],后面有 +08:00

您可以在日期时间中附加 UTC 小时和分钟偏移量:

// import 'package:intl/intl.dart' as intl show DateFormat;

void main() {
  DateTime now = DateTime.now();
  Duration offset = now.timeZoneOffset;

  // ----------
  String dateTime = now.toIso8601String();
  // - or -
  // String dateTime = intl.DateFormat("yyyy-MM-dd'T'HH:mm:ss").format(now);
  // ----------
  String utcHourOffset = (offset.isNegative ? '-' : '+') +
    offset.inHours.abs().toString().padLeft(2, '0');
  String utcMinuteOffset = (offset.inMinutes - offset.inHours * 60)
    .toString().padLeft(2, '0');

  String dateTimeWithOffset = '$dateTime$utcHourOffset:$utcMinuteOffset';
  print(dateTimeWithOffset);
}
Run Code Online (Sandbox Code Playgroud)

我正在使用 DateFormat 类

DateFormat ( https://api.flutter.dev/flutter/intl/DateFormat-class.html ) 不格式化 UTC 时区偏移量。虽然文档中的字母“Z”似乎提供了 UTC 时区偏移量,但它是保留的,您不能使用它,DateFormat("Z")因为它会引发未实现的错误(https://api.flutter.dev/flutter/dart-core/UnimplementedError ) -class.html)。请注意,“Z”(发音为“zulu”)代表零子午线时间,并且 UTC 时区偏移量为 +0:00。


  • 请注意“inHours”表达式,因为偏移量可能是半小时 (2认同)