Dart/Flutter:转换时间戳

Moh*_*med 16 dart flutter

我无法找到解决方案,我从firebase获取数据,其中一个字段是时间戳,看起来像这样 - > 1522129071.在swift我能够转换它并使其可读但我不能由于我不知道所有的类和谷歌没有帮助什么不是,所以将代码转换为飞镖.

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
}
Run Code Online (Sandbox Code Playgroud)

我在达特的尝试:

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;
}
Run Code Online (Sandbox Code Playgroud)

它会返回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;
  }
Run Code Online (Sandbox Code Playgroud)

Ale*_*lam 40

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

更改:

var date = new DateTime.fromMicrosecondsSinceEpoch(timestamp);
Run Code Online (Sandbox Code Playgroud)

var date = new DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
Run Code Online (Sandbox Code Playgroud)

  • 不,它仍然显示错误的值。例如,它应该显示 15:50 PM 它显示 11:23 AM 的相同值 1527796211 (2认同)
  • 您仍然有微秒。请注意,Alex已将其更改为“毫秒” (2认同)

Cop*_*oad 35

  • 从毫秒:

    var millis = 978296400000;
    var dt = DateTime.fromMillisecondsSinceEpoch(millis);
    
    // 12 Hour format:
    var d12 = DateFormat('MM/dd/yyyy, hh:mm a').format(dt); // 12/31/2000, 10:00 PM
    
    // 24 Hour format:
    var d24 = DateFormat('dd/MM/yyyy, HH:mm').format(dt); // 31/12/2000, 22:00
    
    Run Code Online (Sandbox Code Playgroud)
  • 来自 Firestore:

    Map<String, dynamic> map = docSnapshot.data()!;
    DateTime dt = (map['timestamp'] as Timestamp).toDate();
    
    Run Code Online (Sandbox Code Playgroud)
  • 将一种格式转换为另一种格式:

    • 12 小时至 24 小时:

      var input = DateFormat('MM/dd/yyyy, hh:mm a').parse('12/31/2000, 10:00 PM');
      var output = DateFormat('dd/MM/yyyy, HH:mm').format(input); // 31/12/2000, 22:00
      
      Run Code Online (Sandbox Code Playgroud)
    • 24 小时至 12 小时:

      var input = DateFormat('dd/MM/yyyy, HH:mm').parse('31/12/2000, 22:00');
      var output = DateFormat('MM/dd/yyyy, hh:mm a').format(input); // 12/31/2000, 10:00 PM
      
      Run Code Online (Sandbox Code Playgroud)

使用intl包(用于格式化)


小智 15

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

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

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

build() {
  return  Text(_ago(document['mytimestamp'])));
}
Run Code Online (Sandbox Code Playgroud)

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


Baw*_*tha 14

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

Timestamp time;
DateTime.fromMicrosecondsSinceEpoch(time.microsecondsSinceEpoch)
Run Code Online (Sandbox Code Playgroud)


Kam*_*esh 10

如何实施:

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);
}
Run Code Online (Sandbox Code Playgroud)

如何致电:

getCustomFormattedDateTime('2021-02-15T18:42:49.608466Z', 'MM/dd/yy');
Run Code Online (Sandbox Code Playgroud)

结果:

21/02/15

上面的代码解决了我的问题。我希望,这也会对您有所帮助。感谢您提出这个问题。


woo*_*etm 8

嗯,只需使用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
Run Code Online (Sandbox Code Playgroud)

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

final DateTime timeStamp = DateTime.fromMillisecondsSinceEpoch(1546553448639);
Run Code Online (Sandbox Code Playgroud)


Moh*_*med 7

需要任何人的完整代码:

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;
  }
Run Code Online (Sandbox Code Playgroud)

谢谢Alex Haslam的帮助!


Pau*_*elo 7

To convert Firestore Timestamp to DateTime object just use .toDate() method.

Example:

Timestamp now = Timestamp.now();
DateTime dateNow = now.toDate();
Run Code Online (Sandbox Code Playgroud)

As you can see in docs


小智 7

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

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;
   }
Run Code Online (Sandbox Code Playgroud)


小智 5

只要确保乘以正确的因子:

微:乘以1000000(即 10 的 6 次方)

毫:乘以1000(即 3 的 10 次方)

这是它在Dart 中的样子:

var date = new DateTime.fromMicrosecondsSinceEpoch(timestamp * 1000000);
Run Code Online (Sandbox Code Playgroud)

或者

var date = new DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
Run Code Online (Sandbox Code Playgroud)


Alb*_*t M 5

假设时间戳 firestore 中的字段称为时间戳,在 dart 中您可以在返回的映射上调用 toDate() 方法。

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


Rah*_*aha 5

只需调用此方法即可以字符串形式返回所需的日期时间值。

String parseTimeStamp(int value) {
    var date = DateTime.fromMillisecondsSinceEpoch(value * 1000);
    var d12 = DateFormat('MM-dd-yyyy, hh:mm a').format(date);
    return d12;
}
Run Code Online (Sandbox Code Playgroud)

示例:如果您传递 TimeStamp 值1636786003,您将得到的结果为

11-12-2021, 10:46PM
Run Code Online (Sandbox Code Playgroud)