Home > front end >  Convert unix timestamp to specific timezone
Convert unix timestamp to specific timezone

Time:11-05

I have an timestamp in unix like below which is in 2:00 timezone, but I want to get this same date but in 0:00 timezone, with using dayjs,

console.log("TIMESTAMP: ", dayjs.unix(timestamp).format());
>  TIMESTAMP:  2021-05-20T13:46:07 02:00

console.log("FIXED TIMESTAMP: ", dayjs.unix(timestamp).tz("Europe/London").format());
>  FIXED TIMESTAMP:  2021-05-20T12:46:07 01:00

above I try to do this with tz("Europe/London") but, I don't know why, I've got date in " 01:00" timezone..., Why this function do not return me new timestamp converted to " 0:00"?

Thanks for any help!

CodePudding user response:

Have you tried this plug in?

dayjs().utc().format()

Here is a little sandbox.

Although it wont show you 0:00 timestamp, because it's presented in different ISO standard. Will that work for you?

CodePudding user response:

You have to include a couple of extender libraries for both UTC and Timezone formatting to work in dayjs. Both the UTC and Timezone Javascript files are required . I used version 1.10.7 because those were the most up to date.

If you're working in a browser include the following source. HTML:

<script src="https://unpkg.com/[email protected]/dayjs.min.js"></script>
<script src="https://unpkg.com/[email protected]/plugin/utc.js"></script>
<script src="https://unpkg.com/[email protected]/plugin/timezone.js"></script>

JavaScript:

dayjs.extend(window.dayjs_plugin_utc);
dayjs.extend(window.dayjs_plugin_timezone);

let printFormat = 'hh:mm:ssA';
let nowLocal = dayjs().utc().local().format(printFormat);
console.log(nowLocal);
console.log(dayjs().tz("America/New_York").format(printFormat));
console.log(dayjs().tz("Asia/Tokyo").format(printFormat));

A couple of notes for your attempt, the 'tz' (Timezone) object does not hang off the unix() function, it is attached directly to the top level dayjs object. The above example takes the local time, and prints it in three different time zones each in the format hh:mm:ssAM|PM . The unix function takes an Unix timestamp and returns a DayJS object.

Here's a JSFiddle with the above example running: https://jsfiddle.net/e4x507p3/2/

Note, if you're using extensions in a browser, this should work, there is a different method required if you're working in NodeJS: https://day.js.org/docs/en/plugin/loading-into-nodejs

  • Related