Datetime timezone deserialization

回眸只為那壹抹淺笑 提交于 2021-02-07 13:41:20

问题


I've developed a Rest API for my app. It sends to the app dates in the following format 2018-09-07T17:29:12+02:00, where I guess +2:00 represents my timezone as part of one object.

In my Flutter app, once I deserialize the received object, it substracts two hours to the actual received DateTime object.

The class I'm trying to deserialize is defined as follows:

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);
} 

回答1:


DateTime can only represent local time and UTC time.

It supports timezone offset for parsing, but normalizes it to UTC

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

prints true.

You can then only convert between local and UTC time using toLocal() or toUtc()




回答2:


Try calling the .toLocal() method on the date when you deserialize it.

This is what the docs say

Use the methods toLocal and toUtc to get the equivalent date/time value specified in the other time zone.



来源:https://stackoverflow.com/questions/52318867/datetime-timezone-deserialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!