Home > OS >  how to convert date object to string using javascript
how to convert date object to string using javascript

Time:03-29

I have a date object as follows let dateObj = Sat May 01 2021 20:21:00 GMT-0700 (Pacific Daylight Time)

I want to convert above value in this string format. let stringVal = 2021-05-01T20:21:00.000 0000

can someone let me know how to achieve this. i Have tried toUTCString(), to DateString(), toISOString() and all other methods but i was not able to achieve the result in the format above.

Any guidance is appreciated. is it even possible ?

CodePudding user response:

Not sure if you wanted it converted to UTC, but based on your example it looks like not.

Maybe something like this? Just replace "new Date()" with your date object.

const date = new Date(new Date() - 1000 * 60 * 60 * 7); // subtract 7 hours since .toISOString() is going to add 7 hours
console.log(date.toISOString().replace('Z',' 0000'));

* I should add this assumes the client's timezone is Pacific Daylight Time, or a least something with the same offset

  • Related