How To Display UTC Date In Javascript

Carlos Lam

Software Engineer

1 min

Article Banner

Overview

Sometimes, you just want to display a date without a particular timezone in mind. You pass in a date string along the lines of "2023-01-01" to the built-in Date constructor, and what you get is:

1const dateString = "2023-01-01"
2const date = new Date(dateString)
3
4console.log(date)
5//Sat Dec 31 2022 19:00:00 GMT-0500 (Eastern Standard Time)

The date logged/displayed changes to December 31st of the previous year. While this is technically correct if we assume the date string to be in UTC, it may not have been what you intended to display (January 1st).

Solution

If the format Sat Jan 01 2023 00:00:00 GMT works for your use case, then simply displaying with the built-in function toUTCString() will suffice.

But if you need a specific format and want to depend on packages for their formatting functions, then you can convert the Date object's date value to your intended date, in your timezone. For our solution, we will be using date-fns for formatting and time conversion.

1import {format, addMinutes} from 'date-fns'
2
3const date = new Date("2023-01-01");
4const newDate = addMinutes(date, date.getTimezoneOffset());
5
6console.log(format(newDate, "MMM dd yyyy"));
7// Jan 01 2023