How do I save DateTime from Flutter's DateTimePicker and write to Firebase as a Timestamp

Viewed 2155

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);
    });
  });
2 Answers

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

I figured it out. I saw a post on this google groups It was well in line with Er1's earlier suggestion.

For anyone seeking, here's the hack:

  Timestamp _dateTimeToTimestamp(DateTime dateTime) {
    return Timestamp.fromMillisecondsSinceEpoch(
        dateTime.millisecondsSinceEpoch);
  }

onTap: () {
  showDatePicker(
          context: context,
          initialDate: widget.isUpdating
              ? _currentExpense.updatedAt.toDate()
              : DateTime.now(),
          firstDate: DateTime(2001),
          lastDate: DateTime.now())
      .then((date) {
    _dateTime = date;
    print(_dateTime);

    setState(() {
      dateTimeText = _dateTimeToString(_dateTime);

      if (widget.isUpdating) {
        _currentExpense.updatedAt = _dateTimeToTimestamp(_dateTime);
      } else {
//this is new entry
        _currentExpense.createdAt = _dateTimeToTimestamp(_dateTime);
        _currentExpense.updatedAt = _dateTimeToTimestamp(_dateTime);
        }
     });
   });
    
Related