日期时间时区反序列化

pit*_*zzo 8 timezone dart flutter

我为我的应用开发了一个 Rest API。它以以下格式向应用程序发送日期2018-09-07T17:29:12+02:00,我猜 +2:00 将我的时区表示为一个对象的一部分。

在我的 Flutter 应用程序中,一旦我反序列化接收到的对象,它就会将实际接收到的 DateTime 对象减去两个小时。

我试图反序列化的类定义如下:

import 'package:json_annotation/json_annotation.dart';

part 'evento.g.dart';

@JsonSerializable(nullable: false)
class Evento {
  final int id;
    final String nombre;
    final String discoteca;
    final int precio_desde;
    final int edad_minima;
    final DateTime fecha_inicio;
    final DateTime fecha_fin;
    final DateTime fecha_fin_acceso;
    final String cartel;
  final bool incluyeCopa;
    Evento(this.id, this.nombre, this.discoteca, this.precio_desde, this.edad_minima, this.fecha_inicio, this.fecha_fin, this.fecha_fin_acceso, this.cartel, this.incluyeCopa, this.num_tipos);
  factory Evento.fromJson(Map<String, dynamic> json) => _$EventoFromJson(json);
  Map<String, dynamic> toJson() => _$EventoToJson(this);
} 
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 24

DateTime 只能表示本地时间和UTC时间。

它支持用于解析的时区偏移量,但将其标准化为 UTC

print(DateTime.parse('2018-09-07T17:29:12+02:00').isUtc);
Run Code Online (Sandbox Code Playgroud)

打印true

然后,您只能使用toLocal()或在本地时间和 UTC 时间之间进行转换toUtc()


Seb*_*ian 11

尝试调用 .toLocal()在反序列化的日期方法。

这就是文档所说的

使用 toLocal 和 toUtc 方法获取在其他时区中指定的等效日期/时间值。


awa*_*aik 8

另一种使用 json_serialized 并冻结的方法。

创建一个用于转换日期时间的类。

import 'package:freezed_annotation/freezed_annotation.dart';

class DatetimeJsonConverter extends JsonConverter<DateTime, String> {
  const DatetimeJsonConverter();

  @override
  DateTime fromJson(String json) => DateTime.parse(json).toLocal();

  @override
  String toJson(DateTime object) => object.toUtc().toIso8601String();
}
Run Code Online (Sandbox Code Playgroud)

之后,只需将其添加到类中的每个 DateTime 属性中即可。

@DatetimeJsonConverter() @JsonKey(name: 'created_at') required DateTime createdAt,
Run Code Online (Sandbox Code Playgroud)

并相应地转换为 Local\UTC 时间。

  • 谢谢!!!当使用 JsonSerialized 的自动化工具覆盖默认行为以将 json 时间反序列化为 utc 时,这是正确的解决方案。在我看来,这应该是默认行为。 (2认同)