- The time retrieved from the server is in UTC.
- The time to be displayed on the web is not UTC but the visitor's local time.
- Convert and then display.
For local time conversion, most people use libraries. Here, we'll look at how to do this using "dayjs", which is one of the commonly used libraries.# How to get local time from UTC using dayjs
First, let's assume the time retrieved from the server through an API is as follows:
let utcTime = '2023-07-31T12:00:00Z';
Now, we need to convert the aforementioned time using dayjs
. For this purpose, dayjs provides an extension plugin named dayjs-plugin-utc that can handle UTC times
. You can use it as shown below with the extend()
const dayjs = require('dayjs');
const utc = require('dayjs-plugin-utc');
With this, it has now become possible to convert using UTC to the desired local time. We apply the above utcTime variable and utilize the local() method to retrieve the local time.
// Set UTC time to dayjs
let utcDate = dayjs.utc(utcTime);
// Switch UTC time to local time with local() method
let localTime = utcDate.local();
// Print with console.log
Now, if you check the console output, you can obtain the converted local time. Typically, one wouldn't use it as is, but would adjust to a desired format. In reality, you might use it as shown below. The following demonstrates how to display it in the year-month-day hour:minute:second format.
let localTime = utcDate.local().format('YYYY-MM-DD HH:mm:ss');
This allows you to display in a variety of formats.
So far, we have briefly looked at how to obtain local time using dayjs().