I am trying to add a event to my cloud firestore database. However, when I add the event, the date is added as a string whereas in my database, I am using TimeStamp. This is my current code:

class _FirstRoute extends State<FirstRoute> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: StreamBuilder(
          stream: FirebaseFirestore.instance
              .collection('icons')
              .snapshots(),
          builder: (context, snapshot) {
            if (!snapshot.hasData) return Text('Loading data... Please Wait');
            return Padding(
              padding:
                  const EdgeInsets.symmetric(horizontal: 5.0, vertical: 5.0),
              child: new Container(
                child: new ListView(
                  children: <Widget>[
                    new StreamBuilder(
                        stream: FirebaseFirestore.instance
                            .collection('tasksDue')
                            .snapshots(),
                        builder: (context, snapshot) {
                          if (!snapshot.hasData)
                            return Text('Loading data... Please Wait');
                          return Container(
                              child: new Row(children: <Widget>[
                                new Expanded(
                                    child: SizedBox(
                                  child: new ListView(
                                    children: snapshot.data.documents
                                        .map<Widget>(
                                            (DocumentSnapshot document) {
                                      if (document.data()['complete'] != true) {
                                        var now = DateTime.now();
                                          return new Card(
                                              child: new Column(
                                                children: <Widget>[
                                                  new Container(

                                          return new Card(
                                              child: new Column(
                                                children: <Widget>[
                                                  new Container(
                                                    child: new Text(
                                                      document.data()['title'],
                                                      ),
                                                  ),
                                                  new ButtonBar(
                                                    children: <Widget>[
                                                      RaisedButton(
                                                        onPressed: () {
                                                          _sendToServer(
                                                              document.data()[
                                                                  'title'],
                                                              document.data()[
                                                                  'description'],
                                                              now);
                                                          updateData('tasksDue',
                                                              (document.id), {
                                                            'complete': true
                                                          });
                                                        },

So I have set var now = DateTime.now(); and then called this in _sendToServer

_sendToServer(title, description, eventDate) {
    var id;
    FirebaseFirestore.instance.runTransaction((Transaction transaction) async {
      CollectionReference reference =
          FirebaseFirestore.instance.collection('Events');

      await reference.add({
        "title": "$title",
        "description": "$description",
        "id": "$id",
        'event_date': "$eventDate"
      });
      Navigator.pop(context);
    });
  }

When I do this though it adds dateTime as a sting then I get the error Class 'String' has no instance method 'toDate'. as I call the value somewhere else with .toDate()

I have looked at other posts like this but the solutions didn't work. If anyone has any suggestions, I would really appreciate it! Thanks.


Solution 1: Frank van Puffelen

You're adding the date/timestamp to the database with:

'event_date': "$eventDate"

Since you enclose eventData in " marks here, it gets converted to a string.

To pass the raw value of the data:

'event_date': DateTime.fromMillisecondsSinceEpoch(eventDate)

You can also let Firestore set the timestamp of the server, which ensures the vale is affected by any offsets in the user's device time, with:

'event_date': FieldValue.serverTimestamp()