简体   繁体   中英

trying to create a human readable date / time from a firestore timestamp

working on converting a firestore timestamp into something that people will actually want to look at. I'm attempting to do so with the luxon npm package.

the date is coming to my front end in a JSON string with the timestamp format converted to the javascript date object using the timestamp.toDate() method.

created: JSON.stringify(data.created.toDate()),

if i parse this on the front end with JSON.parse() I am left with the following string:

2022-08-17T01:29:41.985Z

i want to use Luxon to format this string into something like 08/17/22 1:29am and then ultimately have this value be sortable in a table..

let me know if you need to see anything else

thanks


the code below is what i'm passing each firestore document through before i return an object from the getserversideprops function. do i want to do the luxon formatting in this function? or do i want to keep the stringify bit and reformat the code on the front end?

export function postToJSON(doc: any) {
  try {
    const data = doc.data();
    return {
      ...data,
      pickDate: JSON.stringify(data.pickDate.toDate()),
      dropDate: JSON.stringify(data.dropDate.toDate()), // old
      created: data.created.toDate(), // new?
    };
  } catch (error) {
    console.error(error);
  }
}

Once you call toDate() on the Firestore timestamp, you get a regular JavaScript Date object. So if you remove the JSON.stringify(...) call, all Luxon functionality for formatting dates should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM