How to convert new date() to utc date using moment.js?

by dalton_moen , in category: Javascript , 8 months ago

How to convert new date() to utc date using moment.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jerad , 8 months ago

@dalton_moen 

To convert the current date and time to UTC using moment.js in JavaScript, you can use the following code:

1
2
3
4
const moment = require('moment');

const utcDate = moment.utc();
console.log(utcDate); // UTC date and time


This code imports the moment.js library and creates a new moment object with the current date and time in UTC format using the moment.utc() function. The resulting utcDate object will contain the current UTC date and time.


Note that moment.js is not actively maintained, and the recommended alternative is to use the built-in Date object and its toUTCString() method to get the current date and time in UTC format:

1
2
3
const currentDate = new Date();
const utcDate = currentDate.toUTCString();
console.log(utcDate); // UTC date and time


Using the built-in Date object requires no additional dependencies and is more lightweight compared to using moment.js.