firebase Flutter无法将Firestore时间戳转换为日期时间

mwg9r5ms  于 2023-01-02  发布在  Flutter
关注(0)|答案(4)|浏览(153)

尝试在Flutter中将Firestore时间戳转换为DateTime时,我总是遇到错误,尝试了所有解决方案,但均无效(上次尝试How to print Firestore timestamp as formatted date and time
下面是我的代码;

    • 代码**
factory UserModel.fromMap(Map<String, dynamic> map) {
    return UserModel(
      name: map['name'],
      email: map['email'],
      username: map['username'],
      registerDate:
          DateTime.fromMillisecondsSinceEpoch(map['registerDate'] * 1000),
      id: map['id'],
      imageUrl: map['imageUrl'],
      cvUrl: map['cvUrl'],
      phoneNumber: map['phoneNumber'],
      education: Education.fromMap(map['education']),
      location: Location.fromMap(map['location']),
      lookingForIntern: map['lookingForIntern'],
    );
  }
    • 错误**
'Timestamp' has no instance method '*'.
Receiver: Instance of 'Timestamp'

已将日期时间转换为时间戳,并已更改

registerDate:
              DateTime.fromMillisecondsSinceEpoch(map['registerDate'] * 1000),

registerDate:map['registerDate']

现在得到下面的错误;

Converting object to an encodable object failed: Instance of 'Timestamp'

但是print(map['registerDate'])打印Timestamp(seconds=1632412800, nanoseconds=0)

mgdq6dx1

mgdq6dx11#

试试这个软件包来处理这个问题-
https://pub.dev/packages/date_format

import 'package:date_format/date_format.dart';

     DateTime datetime = stamp.toDate();
        var time = formatDate(datetime, [hh, ':', nn, ' ', am]);
2eafrhcq

2eafrhcq2#

我有一个firebase函数,它在字段dueDateLatestRental中返回一个时间戳(admin.firestore.Timestamp):

return {
                    data: { 'rental': null, 'hash': null, 'dueDateLatestRental': dueDateLatestRental },
                    status: 403,
                    message: itemStatus

在我的flutter代码中,我这样解析时间戳:

try {
          dynamic dueDateLatestRental = result.data['data']['dueDateLatestRental'];
          final data = Map<String, dynamic>.from(dueDateLatestRental) as Map<String, dynamic>;
          DateTime dueDateLatestRentalString = DateTime.fromMillisecondsSinceEpoch(data['_seconds'] * 1000).toLocal();
          String formattedDueDate = formatDate(dueDateLatestRentalString, [dd, '.', mm, '.', yyyy, ' ', HH, ':', nn]);
          logger.i('addRental result: $formattedDueDate');
            QuickAlert.show(
              context: context,
              type: QuickAlertType.error,
              title: 'Nicht verfügbar',
              text:
              'Das Teil ist bis zum $formattedDueDate ausgeliehen.',
              confirmBtnText: 'Okay',
              onConfirmBtnTap: () async {
                log("Box was not opened");
                Navigator.pop(context);
              },);
            return null;
        } catch (e) {
          logger.e("Error: could not parse the dueDateLatestRental");
          QuickAlert.show(
            context: context,
            type: QuickAlertType.error,
            title: 'Nicht verfügbar',
            text:
            'Das Teil ist bereits ausgeliehen. Bitte warte ein paar Tage.',
            confirmBtnText: 'Okay',
            onConfirmBtnTap: () async {
              log("Box was not opened");
              Navigator.pop(context);
            },
          );
          return null;
        }

我认为将其 Package 在try/catch中会更安全,因为随着时间的推移,有许多方法可以阻止它(例如,我更改数据库结构中的某些内容)
这是生成的警报对话框:

91zkwejq

91zkwejq3#

根据不同的场景,可以采用不同的方法来实现这一点,请查看以下哪段代码适合您的场景。
1.

map['registerDate'].toDate()
(map["registerDate"] as Timestamp).toDate()
DateTime.fromMillisecondsSinceEpoch(map['registerDate'].millisecondsSinceEpoch);
Timestamp.fromMillisecondsSinceEpoch(map['registerDate'].millisecondsSinceEpoch).toDate();

1.在dart文件中添加以下函数。

String formatTimestamp(Timestamp timestamp) {
  var format = new DateFormat('yyyy-MM-dd'); // <- use skeleton here
  return format.format(timestamp.toDate());
}

就叫它formatTimestamp(map['registerDate'])

sqyvllje

sqyvllje4#

  • datetime用于存储服务器当前所在时区,timestamp类型用于将服务器当前时间转换为UTC(世界时间)进行存储
  • 可以将Firestore文档参数类型设置为int
@JsonKey(fromJson: timeFromJson, toJson: timeToJson)
  DateTime fileCreateTime;

  static DateTime timeFromJson(int timeMicroseconds) =>
      Timestamp.fromMicrosecondsSinceEpoch(timeMicroseconds).toDate().toLocal();
  static int timeToJson(DateTime date) =>
      Timestamp.fromMillisecondsSinceEpoch(date.toUtc().millisecondsSinceEpoch)
          .microsecondsSinceEpoch;

相关问题