convert string date and time to utc based on timezone using moment

115 Views Asked by At

am using moment in nodejs server to convert local time from frontend to utc.

my time format is date = '10-07-2020 08:45 PM' in string format. When i use moment(date).format() its converting format to this 2020-10-07 20:45:00+05:30 timezone is adding based on server and i have timezone = '+4:00' this is my local timezone. I would like to convert my date string to UTC based on the timezone field not based on the server timezone. How can I do this?

I tried the following methods but am not getting a proper solution

moment.utc(moment(date).utcOffset(timezone)).format('YYYY-MM-DD HH:mm:ss')

Anyone Please suggest

2

There are 2 best solutions below

0
On

Instead of moment, perhaps use intl DateTimeFormat?

Here are some possibilities

const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric',  hour: 'numeric', minute: 'numeric', second: 'numeric', };

const date = new Date('10-07-2020 08:45 PM')
console.log(date)


options.timeZone = 'Europe/Ulyanovsk';
options.timeZoneName = 'short';
console.log(new Intl.DateTimeFormat('en-US', options).format(date));

1
On

You can use moment-timezone to create a date from a string and a certain timezone. In order to do that you need to specify your format and the corresponding timezone. Something like this:

const date = moment.tz("10-07-2020 08:45 pm", "M-D-YYYY hh:mm a", "Europe/Samara");
console.log(date.toISOString());
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.min.js"></script>