flutter DataTime.parse()的utc时区转换问题

flutter的 DataTime.parse(formattedString)能接收一个格式化后的时间(如 “2019-02-12 12:22:33”), 并返回DateTime格式的一个时间.

但是如何将一个utc格式的时间转为本地时间(北京时间,东8区时间)呢?

例如我需要将UTC时间 “2019-03-02T12:25:55.010Z”转化为(北京时间,东8区时间).

解决思路:

  1. 查看flutter的DataTime.parse的源代码,可以发现这一段注解
   * * An optional time-zone offset part,
   *   possibly separated from the previous by a space.
   *   The time zone is either 'z' or 'Z', or it is a signed two digit hour
   *   part and an optional two digit minute part. The sign must be either
   *   "+" or "-", and can not be omitted.
   *   The minutes may be separated from the hours by a ':'.
   *   Examples: "Z", "-10", "01:30", "1130".
   *
   * This includes the output of both [toString] and [toIso8601String], which
   * will be parsed back into a `DateTime` object with the same time as the
   * original.
   *
   * The result is always in either local time or UTC.
   * If a time zone offset other than UTC is specified,
   * the time is converted to the equivalent UTC time.
   *
   * Examples of accepted strings:
   *
   * * `"2012-02-27 13:27:00"`
   * * `"2012-02-27 13:27:00.123456z"`
   * * `"2012-02-27 13:27:00,123456z"`
   * * `"20120227 13:27:00"`
   * * `"20120227T132700"`
   * * `"20120227"`
   * * `"+20120227"`
   * * `"2012-02-27T14Z"`
   * * `"2012-02-27T14+00:00"`
   * * `"-123450101 00:00:00 Z"`: in the year -12345.
   * * `"2002-02-27T14:00:00-0500"`: Same as `"2002-02-27T19:00:00Z"`
   */

看到`”2002-02-27T14:00:00-0500″`: Same as `”2002-02-27T19:00:00Z”`这一段,就是说14点偏移往前5个小时就是19点了;

那么, 我需要转化UTC时间 “2019-03-02T12:25:55.010Z”, 就必须要符合它上面列出来的格式.

首先要把”.010Z”删除, 加上”-0800″, (“-“代表向东边偏移,”+”代表向西边偏移,”08″代表8个小时,”00″代表分钟);

String utcTime="2019-03-02T12:25:55.010Z";
DataTime beijingTime=DateTime.parse("${utcTime.substring(0,19)}-0800");

    原文作者:ddd打点滴
    原文地址: https://zhuanlan.zhihu.com/p/58135333
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞