How to convert date without timezone

72 Views Asked by At

how to convert date without timezone?

data from the backend comes in the format

1701699255

I'm trying to execute code like this

new Date((1701699255 * 1000) - new Date().getTimezoneOffset() * 60000)

but it still gives me data in timezone format. How can I do it correctly?

2

There are 2 best solutions below

3
mandy8055 On

As far as I understood your requirement; you want to convert the timestamp to a date string without timezone, for which you can use the toISOString() method and then remove the timezone information from the resulting string.

const timestamp = 1701699255;
const date = new Date(timestamp * 1000);
const dateString = date.toISOString().replace(/T/, ' ').replace(/\..+/, '');
console.log(dateString); // "YYYY-MM-DD HH:mm:ss" without timezone information.


Another approach is to use getUTC* methods in case you want to keep the Date object and display it without timezone.

const timestamp = 1701699255;
const date = new Date(timestamp * 1000);

const year = date.getUTCFullYear();
const month = (date.getUTCMonth() + 1).toString().padStart(2, '0');
const day = date.getUTCDate().toString().padStart(2, '0');
const hours = date.getUTCHours().toString().padStart(2, '0');
const minutes = date.getUTCMinutes().toString().padStart(2, '0');
const seconds = date.getUTCSeconds().toString().padStart(2, '0');

const dateString = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
console.log(dateString);

0
Pawan chandra Upreti On

const str = new Date().toLocaleString('en-US', { timeZone: 'Asia/Jakarta' }); console.log(str);