I need to send a post
request to the REST API where it includes a Date
value. However the REST API and MySQL accepts a Timestamp
. Below is how I prepare my current date
User user = User(
name: nameTxtController.text,
email: emailTxtController.text,
phone: mobileTxtController.text,
userLanguage: userLanguage,
userRights: userRight,
lastUpdated: DateTime.now(),
dateCreated: DateTime.now()
);
How to convert this to Timestamp
?
To get date time from a given timestamp, we can use the DateTime. fromMillisecondsSinceEpoch or DateTime. fromMicrosecondsSinceEpoch constructor. We have to multiply the timestamp input by 1000 because DateTime.
In order to get the timestamp in milliseconds from DateTime . Just use the millisecondsSinceEpoch property. Remember that this isn't a callable function rather a property. DateTime time = DateTime.
To format DateTime in Flutter using a standard format, you need to use the intl library and then use the named constructors from the DateFormat class. Simply write the named constructor and then call the format() method with providing the DateTime.
1) On pubspec.yaml
Import cloud_firestore plugin with last version
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) On your file.dart
import 'package:cloud_firestore/cloud_firestore.dart';
3) DateTime to TimeStamp / TimeStamp to 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) Console
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
With your code
User user = User(
name: nameTxtController.text,
email: emailTxtController.text,
phone: mobileTxtController.text,
userLanguage: userLanguage,
userRights: userRight,
lastUpdated: myTimeStamp //here
dateCreated: myTimeStamp //here
);
Just do the following
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) class
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With