Thursday, October 20, 2022

[FIXED] How to Add "Z" at the end of date string with moment in javascript and nodejs

Issue

I want to format my date such that the "Z" letter appears at the end of the date.

I've tried many things but nothing seems to be working. i need it to be in the format of "YYYY-MM-DDT00:00:00.000Z" right now it is in this format except for the Z

How can I include the Z at the end using moment, note that i need the date at the start of the day, as in everything after the "T" is 0.

My Code:

   console.log(moment(req.body.to, "YYYY-MM-DD").startOf('day'))

   'from': {$eq:  moment(req.body.from, "YYYY-MM-DD").startOf('day')},

output of the log:

(moment("2022-10-09T00:00:00.000"))

Solution

Taking from the docs you could do:

moment(req.body.to, "YYYY-MM-DD").startOfDay().format("YYYY-MM-DD[T]HH:mm:ss.SSS[Z]")

Escaping characters To escape characters in format strings, you can wrap the characters in square brackets.

Or, since you only want zeroes:

moment(req.body.to, "YYYY-MM-DD").format("YYYY-MM-DD[T00:00:00.000Z]")

Or, since your example indicates that your date is already in YYYY-MM-DD format, why not just do:

`${req.body.to}T00:00:00.000Z`


Answered By - Emil Hernqvist
Answer Checked By - David Marino (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.