如何将 Flutter Date 转换为 TimeStamp?

新手上路,请多包涵

我需要向 REST API 发送 post 请求,其中包含 Date 值。但是 REST API 和 MySQL 接受 Timestamp 。以下是我准备当前日期的方式

User user = User(
      name: nameTxtController.text,
      email: emailTxtController.text,
      phone: mobileTxtController.text,
      userLanguage: userLanguage,
      userRights: userRight,
      lastUpdated: DateTime.now(),
      dateCreated: DateTime.now()

    );

如何将其转换为 Timestamp

原文由 PeakGen 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 335
2 个回答

只需执行以下操作

User user = User(
      name: nameTxtController.text,
      email: emailTxtController.text,
      phone: mobileTxtController.text,
      userLanguage: userLanguage,
      userRights: userRight,
      lastUpdated: DateTime.now().millisecondsSinceEpoch,
      dateCreated: DateTime.now().millisecondsSinceEpoch

    );

for this to work, your user.lastUpdated and user.dateCreated should be of type int in your model ( bean if you are from Java background)班级

原文由 PeakGen 发布,翻译遵循 CC BY-SA 4.0 许可协议

1) 在 pubspec.yaml 上

使用最新版本导入 cloud_firestore 插件

https://pub.dartlang.org/packages/cloud_firestore

 dependencies:
 flutter:
  sdk: flutter

 # The following adds the Cupertino Icons font to your application.
 # Use with the CupertinoIcons class for iOS style icons.
 cupertino_icons: ^0.1.2`enter code here`

 cloud_firestore: ^0.9.13 //import this, with last version

2) 在你的 file.dart 上

import 'package:cloud_firestore/cloud_firestore.dart';

3) DateTime 到 TimeStamp / TimeStamp 到 DateTime

 DateTime currentPhoneDate = DateTime.now(); //DateTime

Timestamp myTimeStamp = Timestamp.fromDate(currentPhoneDate); //To TimeStamp

DateTime myDateTime = myTimeStamp.toDate(); // TimeStamp to DateTime

print("current phone data is: $currentPhoneDate");
print("current phone data is: $myDateTime");

4) 控制台

I/flutter (15177): current phone data is: 2019-04-17 11:28:26.953530
I/flutter (15177): current phone data is: 2019-04-17 11:28:26.953530

用你的代码

User user = User(
  name: nameTxtController.text,
  email: emailTxtController.text,
  phone: mobileTxtController.text,
  userLanguage: userLanguage,
  userRights: userRight,
  lastUpdated: myTimeStamp //here
  dateCreated: myTimeStamp //here
);

原文由 Thales 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题