美文网首页
Flutter转UTC时间注意点 2022-12-26 周一

Flutter转UTC时间注意点 2022-12-26 周一

作者: 勇往直前888 | 来源:发表于2022-12-25 17:40 被阅读0次

    简介

    由于时间存在着时区的差异,所以在涉及到时间比较相关的内容时,统一时区就显得很重要。
    原生提供了,toUtc()方法,可以方便统一时区。

    定义

      /// Returns this DateTime value in the UTC time zone.
      ///
      /// Returns [this] if it is already in UTC.
      /// Otherwise this method is equivalent to:
      ///
      /// ```dart template:expression
      /// DateTime.fromMicrosecondsSinceEpoch(microsecondsSinceEpoch,
      ///                                     isUtc: true)
      /// ```
      DateTime toUtc() {
        if (isUtc) return this;
        return DateTime._withValue(_value, isUtc: true);
      }
    

    代码很简洁。如果已经是utc时间,原样返回;如果是本地时间,那么就调用内部的构造函数,生产一个新的UTC时间返回。

    注意点

    转化之后,返回了一个新对象。原对象本身并没有发生变化。
    举个例子,比如now是一个本地时间,执行了now. toUtc()之后,now仍然是本地时间。
    想要改变now的话,就需要通过赋值的方式:
    now = now. toUtc();

    例子代码

              DateTime now = DateTime.now();
              debugPrint('now: ${now.toString()}');
              now.toUtc();
              debugPrint('now1: ${now.toString()}');
              now = now.toUtc();
              debugPrint('now.toUtc: ${now.toString()}');
    

    打印内容:

    flutter: now: 2022-12-26 17:14:15.159346
    flutter: now1: 2022-12-26 17:14:15.159346
    flutter: now.toUtc: 2022-12-26 09:14:15.159346Z
    

    光执行now.toUtc();并没有把now变为utc,需要执行并赋值才能生效。

    相关文章

      网友评论

          本文标题:Flutter转UTC时间注意点 2022-12-26 周一

          本文链接:https://www.haomeiwen.com/subject/qysgqdtx.html