Lanil Marasinghe
Lanil Marasinghe

Reputation: 2915

DayJS: Format and Convert an ISO Date/Time String to Local Timezone's Date/Time

I'm consuming an API which returns timestamps in this format 2023-02-18T14:54:28.555Z which is an ISO string. I need to format this value to the timezone of the user.

I've tried this: dayjs("2023-02-18T14:54:28.555Z").format('YYYY-MM-DD HH:MM:ss A') // => "2023-02-18 20:02:28 PM"

The above output is incorrect and is 30 minutes behind for +0530 IST Timezone.

But when I input the same string "2023-02-18T14:54:28.555Z" to the JavaScript date constructor, I can see the correct value. new Date("2023-02-18T14:54:28.555Z").toString() // => 'Sat Feb 18 2023 20:24:28 GMT+0530 (India Standard Time)'

How to get the correct formatted value for my Timezone using DayJS?

Tried feeding the ISO string to the DayJS constructor and expected it'll parse it to the current timezone. But the output value is 30 minutes behind.

Upvotes: 2

Views: 23023

Answers (2)

kevintechie
kevintechie

Reputation: 1521

Date.toString() displays the Date according to the local time of the OS. If you need the time to display in a zone other than the local time of the OS, then you'll have to use the DayJS Timezone plugin.

const dayjs = require('dayjs');
const utc = require('dayjs/plugin/utc');
const timezone = require('dayjs/plugin/timezone');

const timestamp = '2023-02-18T14:54:28.555Z';

dayjs.extend(utc);
dayjs.extend(timezone);

// Seattle time because my OS is set to America/Los_Angeles time.
const seattleString = Date(timestamp).toString();

const dayjsLocal = dayjs(timestamp);
const dayjsIst = dayjsLocal.tz('Asia/Calcutta');
const istString = dayjsIst.format('YYYY-MM-DDTHH:mm:ss');

console.log(seattleString); // Sun Feb 19 2023 02:43:42 GMT-0800 (Pacific Standard Time)

console.log(istString); // 2023-02-18T20:24:28

Upvotes: 4

protob
protob

Reputation: 3583

you can use toLocaleString() method:

const timestamp = "2023-02-18T14:54:28.555Z";
const date = new Date(timestamp);


const options = { timeZone: 'Asia/Kolkata' };
const formattedDate = date.toLocaleString('en-US', options);

console.log(formattedDate); 

Upvotes: 1

Related Questions