Dart / Flutter:转换时间戳

时间:2018-05-31 20:22:03

标签: dart flutter

我找不到解决方法,我正在从firebase获取数据,其中一个字段是一个时间戳,看起来像这样 - > 1522129071.如何将其转换为日期?

Swift示例(有效):

func readTimestamp(timestamp: Int) {
    let now = Date()
    let dateFormatter = DateFormatter()
    let date = Date(timeIntervalSince1970: Double(timestamp))
    let components = Set<Calendar.Component>([.second, .minute, .hour, .day, .weekOfMonth])
    let diff = Calendar.current.dateComponents(components, from: date, to: now)
    var timeText = ""

    dateFormatter.locale = .current
    dateFormatter.dateFormat = "HH:mm a"

    if diff.second! <= 0 || diff.second! > 0 && diff.minute! == 0 || diff.minute! > 0 && diff.hour! == 0 || diff.hour! > 0 && diff.day! == 0 {
        timeText = dateFormatter.string(from: date)
    }
    if diff.day! > 0 && diff.weekOfMonth! == 0 {
        timeText = (diff.day == 1) ? "\(diff.day!) DAY AGO" : "\(diff.day!) DAYS AGO"
    }
    if diff.weekOfMonth! > 0 {
        timeText = (diff.weekOfMonth == 1) ? "\(diff.weekOfMonth!) WEEK AGO" : "\(diff.weekOfMonth!) WEEKS AGO"
    }

    return timeText
}

我对达特的尝试:

String readTimestamp(int timestamp) {
    var now = new DateTime.now();
    var format = new DateFormat('HH:mm a');
    var date = new DateTime.fromMicrosecondsSinceEpoch(timestamp);
    var diff = date.difference(now);
    var time = '';

    if (diff.inSeconds <= 0 || diff.inSeconds > 0 && diff.inMinutes == 0 || diff.inMinutes > 0 && diff.inHours == 0 || diff.inHours > 0 && diff.inDays == 0) {
      time = format.format(date); // Doesn't get called when it should be
    } else {
      time = diff.inDays.toString() + 'DAYS AGO'; // Gets call and it's wrong date
    }

    return time;
}

它会返回关闭waaaaaaay的日期/时间。

更新:

String readTimestamp(int timestamp) {
    var now = new DateTime.now();
    var format = new DateFormat('HH:mm a');
    var date = new DateTime.fromMicrosecondsSinceEpoch(timestamp * 1000);
    var diff = date.difference(now);
    var time = '';

    if (diff.inSeconds <= 0 || diff.inSeconds > 0 && diff.inMinutes == 0 || diff.inMinutes > 0 && diff.inHours == 0 || diff.inHours > 0 && diff.inDays == 0) {
      time = format.format(date);
    } else {
      if (diff.inDays == 1) {
        time = diff.inDays.toString() + 'DAY AGO';
      } else {
        time = diff.inDays.toString() + 'DAYS AGO';
      }
    }

    return time;
  }

16 个答案:

答案 0 :(得分:21)

您的时间戳格式实际上是秒(Unix时间戳),而不是微秒。如果是这样,答案如下:

变化:

var date = new DateTime.fromMicrosecondsSinceEpoch(timestamp);

var date = new DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);

答案 1 :(得分:17)

您可以使用intl软件包,先导入

import 'package:intl/intl.dart';

然后

int timeInMillis = 1586348737122;
var date = DateTime.fromMillisecondsSinceEpoch(timeInMillis);
var formattedDate = DateFormat.yMMMd().format(date); // Apr 8, 2020

答案 2 :(得分:7)

如果有人来这里转换Firebase Timestamp,这会有所帮助

Timestamp time;
DateTime.fromMicrosecondsSinceEpoch(time.microsecondsSinceEpoch)

答案 3 :(得分:4)

任何需要它的人的完整代码:

String readTimestamp(int timestamp) {
    var now = new DateTime.now();
    var format = new DateFormat('HH:mm a');
    var date = new DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
    var diff = now.difference(date);
    var time = '';

    if (diff.inSeconds <= 0 || diff.inSeconds > 0 && diff.inMinutes == 0 || diff.inMinutes > 0 && diff.inHours == 0 || diff.inHours > 0 && diff.inDays == 0) {
      time = format.format(date);
    } else if (diff.inDays > 0 && diff.inDays < 7) {
      if (diff.inDays == 1) {
        time = diff.inDays.toString() + ' DAY AGO';
      } else {
        time = diff.inDays.toString() + ' DAYS AGO';
      }
    } else {
      if (diff.inDays == 7) {
        time = (diff.inDays / 7).floor().toString() + ' WEEK AGO';
      } else {

        time = (diff.inDays / 7).floor().toString() + ' WEEKS AGO';
      }
    }

    return time;
  }

谢谢Alex Haslam的帮助!

答案 4 :(得分:3)

如何实施:

import 'package:intl/intl.dart';

getCustomFormattedDateTime(String givenDateTime, String dateFormat) {
    // dateFormat = 'MM/dd/yy';
    final DateTime docDateTime = DateTime.parse(givenDateTime);
    return DateFormat(dateFormat).format(docDateTime);
}

如何调用:

getCustomFormattedDateTime('2021-02-15T18:42:49.608466Z', 'MM/dd/yy');

结果:

02/15/21

以上代码解决了我的问题。我希望,这也能帮助你。感谢您提出这个问题。

答案 5 :(得分:2)

嗯,只需使用https://github.com/andresaraujo/timeago.dart库即可;它为您完成了所有繁重的工作。

编辑:

从您的问题来看,您似乎想要相对的时间转换,并且 timeago 库使您可以在1行代码中完成此操作。转换日期不是我要自己实现的事情,因为存在很多极端情况,而且转换起来很快,特别是在将来需要支持其他语言环境时。您编写的代码更多=您必须测试的代码更多。

import 'package:timeago/timeago.dart' as timeago;

final fifteenAgo = DateTime.now().subtract(new Duration(minutes: 15));
print(timeago.format(fifteenAgo)); // 15 minutes ago
print(timeago.format(fifteenAgo, locale: 'en_short')); // 15m
print(timeago.format(fifteenAgo, locale: 'es'));

// Add a new locale messages
timeago.setLocaleMessages('fr', timeago.FrMessages());

// Override a locale message
timeago.setLocaleMessages('en', CustomMessages());

print(timeago.format(fifteenAgo)); // 15 min ago
print(timeago.format(fifteenAgo, locale: 'fr')); // environ 15 minutes

要将epochMS转换为DateTime,只需使用...

final DateTime timeStamp = DateTime.fromMillisecondsSinceEpoch(1546553448639);

答案 6 :(得分:2)

我测试了这个,它有效

// Map from firestore
// Using flutterfire package hence the returned data()
Map<String, dynamic> data = documentSnapshot.data();
DateTime _timestamp = data['timestamp'].toDate();

可以在此处找到测试详细信息:https://www.youtube.com/watch?v=W_X8J7uBPNw&feature=youtu.be

答案 7 :(得分:1)

如果您使用的是Firestore(而不仅仅是将时间戳存储为字符串),则文档中的日期字段将返回时间戳。 Timestamp对象包含一个toDate()方法。

使用timeago,您可以非常简单地创建相对时间:

_ago(Timestamp t) {
  return timeago.format(t.toDate(), 'en_short');
}

build() {
  return  Text(_ago(document['mytimestamp'])));
}

确保将_firestore.settings(timestampsInSnapshotsEnabled: true);设置为返回时间戳而不是日期对象。

答案 8 :(得分:1)

请确保乘以正确的因子:

微型:乘以 1000000 (即10的幂6)

米利:乘以 1000 (10为3的幂)

这是 Dart 中的外观:

var date = new DateTime.fromMicrosecondsSinceEpoch(timestamp * 1000000);

var date = new DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);

答案 9 :(得分:1)

要将Firestore Timestamp转换为DateTime对象,只需使用.toDate()方法。

示例:

Timestamp now = Timestamp.now();
DateTime dateNow = now.toDate();

您在docs中看到

答案 10 :(得分:1)

假设时间戳存储区中的字段称为时间戳,在dart中,您可以在返回的地图上调用toDate()方法。

// Map from firestore
// Using flutterfire package hence the returned data()
Map<String, dynamic> data = documentSnapshot.data();
DateTime _timestamp = data['timestamp'].toDate();

答案 11 :(得分:1)

Timestamp 有 [toDate] 方法,那么您可以直接将其用作 DateTime。

timestamp.toDate();
// return DateTime object

如果你真的想转换它,还有一个愚蠢的方法:

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

答案 12 :(得分:0)

以上所有功能都可以使用,但是要快速简便地修复,您可以使用time_formatter软件包。

使用此软件包,您可以将纪元转换为人类可以理解的时间。

String convertTimeStamp(timeStamp){
//Pass the epoch server time and the it will format it for you 
   String formatted = formatTime(timeStamp).toString();
   return formatted;
}
//Then you can display it
Text(convertTimeStamp['createdTimeStamp'])//< 1 second : "Just now" up to < 730 days : "1 year"

在这里您可以检查将要显示的输出格式:Formats

答案 13 :(得分:0)

如果您只是将Timestamp转换为DateTime,

Timestamp timestamp = widget.firebaseDocument[timeStampfield];
DateTime date = Timestamp.fromMillisecondsSinceEpoch(
                timestamp.millisecondsSinceEpoch).toDate();

答案 14 :(得分:0)

我不知道这是否会帮助任何人。先前的消息对我有帮助,所以我在这里提出一些建议:

import 'package:intl/intl.dart';

    DateTime convertTimeStampToDateTime(int timeStamp) {
     var dateToTimeStamp = DateTime.fromMillisecondsSinceEpoch(timeStamp * 1000);
     return dateToTimeStamp;
   }

  String convertTimeStampToHumanDate(int timeStamp) {
    var dateToTimeStamp = DateTime.fromMillisecondsSinceEpoch(timeStamp * 1000);
    return DateFormat('dd/MM/yyyy').format(dateToTimeStamp);
  }

   String convertTimeStampToHumanHour(int timeStamp) {
     var dateToTimeStamp = DateTime.fromMillisecondsSinceEpoch(timeStamp * 1000);
     return DateFormat('HH:mm').format(dateToTimeStamp);
   }

   int constructDateAndHourRdvToTimeStamp(DateTime dateTime, TimeOfDay time ) {
     final constructDateTimeRdv = dateTimeToTimeStamp(DateTime(dateTime.year, dateTime.month, dateTime.day, time.hour, time.minute)) ;
     return constructDateTimeRdv;
   }

答案 15 :(得分:0)

Assuming you have a class

class Dtime {
  int dt;
  Dtime(this.dt);

  String formatYMED() {
    var date = DateTime.fromMillisecondsSinceEpoch(this.dt);
    var formattedDate = DateFormat.yMMMMEEEEd().format(date);
    return formattedDate;
  }

  String formatHMA() {
    var time = DateTime.fromMillisecondsSinceEpoch(this.dt * 1000);
    final timeFormat = DateFormat('h:mm a', 'en_US').format(time);
    return timeFormat;
  }

虽然我是初学者,但我希望有用。