【问题标题】:How to save a timestamp in firestore如何在firestore中保存时间戳
【发布时间】:2021-02-19 12:34:20
【问题描述】:

我将下面显示的地图保存到 Firestore,但我还想保存一个时间戳,该时间戳应该包含用户使用日期和时间选择器选择的时间和日期。日期已经采用“dd.MM.yyyy”格式,时间类似于“6:58 PM”。日期是变量date,时间是变量time。如何保存值为timedate 的时间戳?

Map<String, dynamic> data = {
      'name': userName,
      'userUID': userUIDglobal,
      'time: '//here I want to safe the timestamp
    };
    Firestore.instance
        .collection('seller')
        .document(documentID)
        .collection('test')
        .add(data);
  }

【问题讨论】:

    标签: flutter dart google-cloud-firestore timestamp


    【解决方案1】:

    如果你想使用服务器生成的值,这样你不依赖设备时间会更好,使用这个:

        Map<String, dynamic> data = {
          'name': userName,
          'userUID': userUIDglobal,
          'time': FieldValue.serverTimestamp(),
        };
        Firestore.instance
            .collection('seller')
            .document(documentID)
            .collection('test')
            .add(data);
    

    但请注意,如果您在将此文档写入集合时拥有一个活动的集合快照订阅,您将获得一个具有null 值为time 的快照(因为乐观提交),然后当您从服务器获取数据你会得到实际的毫秒值。

    编辑:您可以通过将此写入作为事务的一部分来防止乐观提交为时间戳发出 null 值。

    【讨论】:

      【解决方案2】:

      我建议将其转换为纪元时间,因为 int 将其存储在您的云中,并在获取后重新转换为 DateTime。

      例子:

      // Convert DateTime to int
      int time = DateTime.now().millisecondsSinceEpoch;
      
      Map<String, dynamic> data = {
        'name': userName,
        'userUID': userUIDglobal,
        'time': time
      };
      
      // To safely convert it back to DateTime
      
      DateTime fetchedTime = DateTime.fromMillisecondsSinceEpoch(data['time']);
      

      【讨论】:

      • 但是如何使用用户选择的日期和时间?
      • 您可以使用 DateTime 构造函数。构造一个在本地时区中指定的 DateTime 实例。例如,要创建一个表示 2017 年 9 月 7 日下午 5:30 的新 DateTime 对象 var DentalAppointment = new DateTime(2017, 9, 7, 17, 30);
      猜你喜欢
      • 1970-01-01
      • 2021-12-31
      • 2020-02-09
      • 2018-06-22
      • 2018-08-13
      • 2019-12-02
      • 1970-01-01
      • 2019-04-19
      • 1970-01-01
      相关资源
      最近更新 更多