Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moment toISOstring without modifying date

Tags:

momentjs

I have a date like "Thu Sep 01 2016 00:00:00 GMT+0530 (IST)" which I need to send to server as ISO-8601 utc time. I tried like :

moment(mydate).toISOString()

moment.utc(mydate).toISOString()

moment(mydate).utcOffset("+00:00").toISOString() 

but I am getting the result like

2016-08-31T18:30:00.000Z

which is 1day behind my intended time. So what can I do to make moment ignore my local timezone and see it as UTC?

Edit: The expected output is

2016-09-01T18:30:00.000Z

And no, the initial input isn't a string rather a javascript "new Date()" value.

like image 712
Btdev Avatar asked Oct 19 '22 02:10

Btdev


1 Answers

Reason this happens: This happens because .toISOString() returns a timestamp in UTC, even if the moment in question is in local mode. This is done to provide consistency with the specification for native JavaScript Date .toISOString()

Solution: Use the same function and pass true value to it. This will prevent UTC Conversion. moment(date).toISOString(true)

const date = new Date("2020-12-17T03:24:00");
const dateISOStringUTC = moment(date).toISOString();
const dateISOString = moment(date).toISOString(true);

console.log("Converted to UTC:" + dateISOStringUTC)
console.log("Actual Date value:" + dateISOString)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
like image 85
PRATIK NAIK Avatar answered Oct 21 '22 05:10

PRATIK NAIK