Convert UTC to local timezone – Node JS

In this tutorial, we will teach you, how you can convert UTC time to your local timezone in Node JS.

Following code will first get the current datetime in UTC, then convert it to user local timezone.

Note: You do not need to provide the timeZone from client side. Node JS will automatically detect the timeZone from incoming request and convert it accordingly.

let date = new Date()

date = new Date(date + " UTC")
date = date.toUTCString()

result.send(date + "")

If you want to return the datetime in specific format, you can do it like this:

// Options for date and time formatting
const options = {
    weekday: 'long',
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: true
}

const date = (new Date()).toLocaleString("en-US", options)

This will return the date and time in format: “Tuesday, 2 July, 2024 at 05:11:05 pm”.

Check this tutorial if you want to convert UTC to local timezone in Python.

Convert UTC to local timezone – Python

Here’s how you can get the date and time in UTC and convert it to user’s local timezone in Python.

from fastapi import FastAPI
from datetime import datetime, timezone as timezone_module
from dateutil import tz

app = FastAPI()

utc = datetime.now(timezone_module.utc)

# Hardcode zones:
from_zone = tz.gettz("UTC")
to_zone = tz.gettz("Asia/Karachi")

# you can get user's local timezone in Javascript using following code:
# Intl.DateTimeFormat().resolvedOptions().timeZone

# Tell the datetime object that it's in UTC time zone since 
# datetime objects are 'naive' by default
utc = utc.replace(tzinfo=from_zone)

# Convert time zone
local = utc.astimezone(to_zone)

# get in readable format
local = local.strftime("%b %d, %Y %H:%M:%S")

print(local)

Comments has been added with each line for explanation. You can check its real-world example in a URL shortener app we created in Python.