1

I am working in Firebase and writing a Cloud Function in JavaScript. I am trying to extract a Month Day, Year string from a Firebase Timestamp (from my database).

In my Cloud Function I use timestampObj.toDate().toString() and it returns a string like this in my client-side: Fri Dec 06 2019 18:06:52 GMT+0000 (UTC)

How do I get the string December 6, 2019 from the line above in my Dart code?

Mary X
  • 153
  • 2
  • 15
  • Does this answer your question? [convert datetime string to datetime object in dart?](https://stackoverflow.com/questions/49385303/convert-datetime-string-to-datetime-object-in-dart) – jamesdlin May 24 '20 at 03:47
  • No, it does not @jamesdlin – Mary X May 24 '20 at 03:57

2 Answers2

2

Converting the DateTime returned by toDate() into a String sounds like putting yourself through much more trouble than necessary. DateTime has lots of methods for easily extracting the calendar components out of it. You can see from that API doc link that it has properties for year, month, and day that require no text parsing. It should be trivial to convert those into the string format you want.

Even better, you can just use the DateFormat class.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
0

Will this help? Shouldn't the output be "December 6, 2019" instead of December 9?

var date = new Date("Fri Dec 06 2019 18:06:52 GMT+0000 (UTC)");  //

var result = date.toLocaleString('default',{month:'long'})+" "+date.getDate()+", "+date.getFullYear();

console.log(result);   // "December 6, 2019"
Mohsen Alyafei
  • 4,765
  • 3
  • 30
  • 42
  • Thanks for your response but for some reason the Month string that is returned to me says "M12" instead of December like yours does. Do you happen to know why? – Mary X May 24 '20 at 05:50
  • @MaryX Strange. I tried it again with `var date = new Date();` as an input to today's date and output was correct `May 24, 2020` – Mohsen Alyafei May 24 '20 at 05:55
  • 1
    Never mind, I just changed the 'default' to 'en-US'. @Mohsen Alyafei – Mary X May 24 '20 at 05:56