如何在flutter中将Firestore时间戳打印为格式化的日期和时间

时间:2019-06-17 08:52:46

标签: time flutter dart google-cloud-firestore

扑扑的Firestore快照中的时间戳返回aa Timestamp(seconds=1560523991, nanoseconds=286000000)

我要打印格式正确的日期和时间

我使用DateTime.now()将当前的DateTime存储在Firestore中,同时创建新记录并使用Firestore快照进行检索,但我返回的格式值得注意,请转换为格式化的日期时间,以便使用lib intl.dart进行格式化< / p>

用于保存数据的代码

d={'amount':amount,
  'desc':desc,
  'user_id':user_id,
  'flie_ref':url.toString(),
  'date':'${user_id}${DateTime.now().day}-${DateTime.now().month}-${DateTime.now().year}',
  'timestamp':DateTime.now()

返回Firestore.instance.collection('/ data')。add(d).then((v){返回true;     })。catchError((onon)=> print(onError));     });

通过

访问
FutureBuilder(
              future: Firestore.instance
                  .collection('data')
                  .where('user_id', isEqualTo:_user_id)
                  .getDocuments(),
              builder: (BuildContext context,
                  AsyncSnapshot<QuerySnapshot> snapshot) {
                if (!snapshot.hasData)
                  return Container(
                      child: Center(child: CircularProgressIndicator()));
                return ListView.builder(
                    itemCount: snapshot.data.documents.length,
                    itemBuilder: (BuildContext context, int index) {
                      return Column(
                        children: <Widget>[
   Text(DateFormat.yMMMd().add_jm().format(DateTime.parse(snapshot.data.documents[index].data['timestamp'].toString())]);
....

引发错误是无效的日期格式。

我期望输出为:'Jan 17,2019,2:19 PM'

15 个答案:

答案 0 :(得分:6)

您可以像这样直接将Firestore时间戳对象转换为DateTime:

DateTime myDateTime = (snapshot.data.documents[index].data['timestamp']).toDate();

这将以飞镖的DateTime格式返回您的Firestore时间戳。为了转换DateTime对象,可以使用intl包中的DateFormat类。 您可以使用获取的DateTime对象来获取您选择的格式,如下所示:

DateFormat.yMMMd().add_jm().format(myDateTime);

此代码产生如下输出:

Apr 21, 2020 5:33 PM

答案 1 :(得分:3)

我发现 Ashutosh 的建议提供了更多用户友好的输出。推荐在带有静态方法的辅助类中使用这样的函数。

  static convertTimeStamp(Timestamp timestamp) {
    assert(timestamp != null);
    String convertedDate;
    convertedDate = DateFormat.yMMMd().add_jm().format(timestamp.toDate());
    return convertedDate;
  }
DateFormat 需要

Intl 软件包。

答案 2 :(得分:2)

您应该使用 fromMillisecondsSinceEpoch 函数。

var d = new DateTime.fromMillisecondsSinceEpoch(ts, isUtc: true);

ts是int类型。

因此,我们可以将Firebase 时间戳转换为DateTime对象,如下所示。

DateTime date = DateTime.fromMillisecondsSinceEpoch(timestamp.seconds * 1000);

答案 3 :(得分:0)

即使将DateTime发送到Firestore,您也将从Firestore获取Unix时间戳。

您可以使用DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);来解析Firestore中的DateTime

DateTime类具有两个返回字符串的选项。 toIso8601String()toString() 选择您需要的那个。或使用例如。 DateTime.now()。hour;得到我们的并创建自己的输出。

有关更多信息:选中https://api.dartlang.org/stable/2.4.0/dart-core/DateTime-class.html

答案 4 :(得分:0)

timestamp参数是以秒为单位的时间

String formatTimestamp(int timestamp) {
      var format = new DateFormat('d MMM, hh:mm a');
      var date = new DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
      return format.format(date);
    }

请检查this答案的国际日期格式

希望有帮助!

答案 5 :(得分:0)

当我们将 DateTime 对象推入Firestore时,它将在内部将其转换为自己的 timestamp 对象并进行存储。

从Firestore获取时间戳后将其转换回Datetime的方法:

Firestore的 timestamp 包含一个名为 toDate()的方法,该方法可以转换为String,然后可以将该String传递给 DateTime parse 方法转换回 DateTime

DateTime.parse(timestamp.toDate().toString())

答案 6 :(得分:0)

这样做:

DateFormat.yMMMd().add_jm().format(DateTime.parse(snapshot.data.documents[index].data['timestamp'].toDate().toString())]

答案 7 :(得分:0)

这是路!

Firestore将像时间戳一样返回时间戳(秒= 1560523991,纳秒= 286000000)。

这可以解析为

window.onload = function() {
    var puURL = 'https://google.com';
    var puTS = Math.round(+new Date()/1000);
    //var puDate = currentDate.getDate().toString(); //day
    console.log('T.'+localStorage.puTS+'/'+puTS);
    if (typeof localStorage.puTS == 'undefined' || parseInt(localStorage.puTS) <= (puTS - 3600)) {
        console.log('Yep');
        var links = document.getElementsByTagName('a');
        for(var i = 0, len = links.length; i < len; i++) {
          links[i].onclick = function (e) {
              var puHref = this.getAttribute("href");
                var puTarget = this.getAttribute("target");
                if (puHref !== '#' && puHref !== 'javascript:void(0)') {
                e.preventDefault();    
                if (puTarget == '_blank') {
                    window.open(window.location.href);
                }
                window.open(puHref);
                window.location.href = puURL;
                localStorage.puTS = puTS;
              }
            }
        }
    }
};

答案 8 :(得分:0)

首次访问here获取国际包, 然后将该软件包粘贴到您的pubspec.yaml中,运行pub get(更新pubspec的常用方法)。将该软件包导入到dart文件中,然后尝试以下方法。

String timestamp;

DateTime now = DateTime.now();
String formatDate =
    DateFormat('yyyy-MM-dd – kk:mm').format(now);
timestamp = formatDate;

答案 9 :(得分:0)

一旦您从Firestore获得了时间戳,类似

时间戳(秒= 1560523991,纳秒= 286000000)

您需要将其解析成日期时间类型的对象:

DateTime myDateTime = DateTime.parse(timestamp.toDate().toString());

 print('$myDateTime');

这将为您提供以下信息:

2020-05-09 15:27:04.074

然后您可以像这样格式化myDateTime:

String formattedDateTime =
          DateFormat('yyyy-MM-dd – kk:mm').format(myDateTime);

print('$formattedDateTime');

这将为您提供:

2020-05-09 – 15:27

答案 10 :(得分:0)

简单的解决方法。

//声明一个变量Timestamp并从数据库中分配timestamp值

Timestamp timestamp = document['timeFieldName'];

//使用DateTime的解析方法将其转换回DateTime

DateTime _time =DateTime.parse(timestamp.toDate().toString())

//使用此方法获取DateTime的H:m。 //您可以选择所需的DateFormat

String readTimeStamp(DateTime date)
  {
    
     var format =new DateFormat.Hm(); // My Format 08:00

     return format.format(date);
  }

答案 11 :(得分:0)

使用Cloud Firestore,这是我的工作方式:

Text(snapshot.data["YouKey"].toDate().toString().substring(0,16))

subString是可选的,我添加了它是因为我的时钟时间在分钟后有很多数字(例如12:00 00:00:00)

答案 12 :(得分:0)

花了很长时间才找到完美的答案。 当您从Firestore中将数据作为Timestamp对象获取时,如果可以确定,那么我建议您使用以下代码:

DateTime fetchedDate = e.data()["deadline"]?.toDate();

使用?.toDate()对我有用,希望对您也有用。

答案 13 :(得分:0)

Timestamp t = document['time'] // Timestamp(seconds=1624653319,nanoseconds=326000000)
DateTime d = t.toDate();
print(d.toString()); //2021-06-25 18:48:48.364

答案 14 :(得分:0)

使用 intl 包:

Timestamp firebaseTimestamp = ...;
var date = firebaseTimestamp.toDate();

var output1 = DateFormat('MM/dd, hh:mm a').format(date); // 12/31, 10:00 PM
var output2 = DateFormat.yMMMd().format(date); // Dec 31, 2000