How to Convert a JavaScript Date to UTC Format

I recently had a problem where I wanted to convert my JavaScript Date to UTC format instead of local server time. In the browser, the Date’s representation will be in the host machine’s local time zone. If you are trying to take a server response Date string and perform logic, then you may experience some wonkiness because of the date-time conversion.

At its center, the JS Date is in UTC.

The crux of what you are looking for is the Date.UTC(), which returns the milliseconds since January 1, 1970.

Creating a UTC Date

// Sun Nov 01 2020 06:18:48 GMT-0500 (Eastern Standard Time)const myDay = newDate(); 
// 1604211528507let inUtc = Date.UTC(mine.getFullYear(), mine.getMonth(), mine.getDate(), mine.getHours(), mine.getMinutes(), mine.getSeconds(), mine.getMilliseconds());
// Sun Nov 01 2020 01:18:48 GMT-0500 (Eastern Standard Time)const myDayFromUtc = newDate(inUtc); // same as myDay

Getting the yyyy-MM-dd Date

If I wanted a Date representing the start of the day, such as 2020-10-30 00:00:00, then the following constructs the date with that value as the UTC version. Most people do not live in UTC, but this creates the date and displaying it will convert it to their local time.

const today = newDate(Date.UTC(today.getFullYear(), today.getMonth(), today.getDate()));

For more in-depth reference on the JavaScript Date object, I recommend reading Mozilla’s web docs.

Leave a Reply

Your email address will not be published. Required fields are marked *