简体   繁体   中英

JavaScript how to convert Europe/Berlin timezone to local timezone date

I have my note module which display notes made by user with date and time , using my API call i am receiving following date

2020-02-08 10:58:00 which is in Europe/Berlin timezone.

now on client side i want to display it in local time zone ie in india it should be like

2020-02-08 03:28:00

i know moment js can do it but i dont know how to use it. so is there any way to do it? using either core javascript or momentjs?

following is what i have tried to get time string using moment js

moment(new Date(targetDateString)).fromNow();

but this always show me time five hours age as my local time zone is ITC and date is store in Europe/Berlin

You can use moment-timezone .

 var date = moment.tz("2020-02-08 10:58:00", "Europe/Berlin"); var localDate = moment.tz("2020-02-08 10:58:00", "Europe/Berlin").local(); console.log('Europe/Berlin', date.format()); console.log('Local', localDate.format());
 <script src="https://momentjs.com/downloads/moment.js"></script> <script src="https://momentjs.com/downloads/moment-timezone-with-data-10-year-range.js"></script>

You need to install moment-timezone from their website ('yarn add' or whatever) and replace your moment with the moment from moment-timezone.

Like this:

import moment from 'moment-timezone';

Change timestamp from London To Berlin Time:
moment.tz(someTimeStamp, 'HHmmss','Europe/London').tz('Europe/Berlin').format('HH:mm:ss')

Change timestamp from UTC to browser's local time:
moment.tz(someTimeStamp, 'HHmmss','UTC').local().format('HH:mm:ss')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM