【问题标题】:Datetime timezone deserialization日期时间时区反序列化
【发布时间】:2018-09-13 17:27:48
【问题描述】:

我为我的应用开发了一个 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);
} 

【问题讨论】:

    标签: dart timezone flutter


    【解决方案1】:

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

    这是文档所说的

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

    【讨论】:

    • 对我来说最好的解决方案
    【解决方案2】:

    DateTime只能代表当地时间和UTC时间。

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

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

    打印true

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-30
      • 1970-01-01
      • 2016-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多