How do I save DateTime from Flutter's DateTimePicker and write to Firebase as a Timestamp
1,855
You can use dateTimeObject.millisecondsSinceEpoch
to convert it to an int
and save that to your db.
And then use DateTime.fromMillisecondsSinceEpoch(msIntFromServer)
to convert it back to a DateTime object.
Or if you want even more accuracy you can do it in microseconds.
https://api.flutter.dev/flutter/dart-core/DateTime-class.html
Comments
-
hermie_brown over 1 year
I am using the DatePicker as below to allow user to set Date. I want to save this selected date and time to Firebase as a Timestamp. How do I do that?
Thanks.
showDatePicker( context: context, initialDate: widget.isUpdating ? _currentExpense.createdAt.toDate() : _dateTime, //_currentExpense.createdAt == null, firstDate: DateTime(2001), lastDate: DateTime.now()) .then((date) { _dateTime = date; setState(() { dateTimeText = _getDateString(date); }); });
-
hermie_brown over 3 yearsThanks! So just to clarify, Timestamp is basically saved as/in milliseconds or microseconds?
-
hermie_brown over 3 yearsAlso, using your suggestion means I have to save _currentExpense.createdAt as an int in my DB and not as a Timestamp? In my setState(), I did, _currentExpense.createdAt = _dateTime.millisecondsSinceEpoch as Timestamp; but it didn't successful save to DB as it expected a Timestamp and I am sending an int as the value.
-
Er1 over 3 years@hermie_brown I'm just saying you could save it as an int. If you already use a specified format for Timestamp in your db you should take a look at the docs from firebase or the library you're using on how to format the timestamp to that format.