Мне нужно отправить запрос post
в REST API, где он включает значение 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
?
Просто сделайте следующее
User user = User(
name: nameTxtController.text,
email: emailTxtController.text,
phone: mobileTxtController.text,
userLanguage: userLanguage,
userRights: userRight,
lastUpdated: DateTime.now().millisecondsSinceEpoch,
dateCreated: DateTime.now().millisecondsSinceEpoch
);
чтобы это работало, ваши user.lastUpdated
и user.dateCreated
должны иметь тип int
в классе вашей модели (bean
, если вы работаете с Java)
чтобы скрыть его -> DateTime.fromMillisecondsSinceEpoch(user.lastUpdated);
метка времени указана в секундах, поэтому вам нужно сделать это: (DateTime.now().millisecondsSinceEpoch / 1000).round()
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) На вашем файле .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
);
Попробуйте это один раз, это сработало для меня
Timestamp.fromDate(DateTime.now())
здесь TimeStamp из пакета Облачный магазин огня и необходимо добавить это в файл pubspec.yaml.
вы также должны упомянуть, как преобразовать его обратно в тип DateTime