简体   繁体   中英

Date in CET timezone to user's timezone

I have a list of list of string dates like this: '17/12/2017 19:34' . They are CET dates.

How can I transform it to the user's browser date?

I'm doing this:

const tzGuess = moment.tz.guess()

export const toTimeZone = (time) => {
  const format = 'DD/MM/YYYY HH:mm'
  return moment(time, format).tz(tzGuess).format(format)
}

console.log(toTimeZone('17/12/2017 19:34', tzGuess))

but how can I say to moment that the date I'm passing at first is a CET one?

Thanks!

Without moment.js, parse the string to a Date, treating it as UTC, then adjust for the CET offset (+0100). You can then format it using local time values for the client:

 // Parse date in format DD/MM/YYYY HH:mm // Adjust for CET timezone function parseCET(s) { var b = s.split(/\\D/); // Subtract 1 from month and hour var d = new Date(Date.UTC(b[2], b[1]-1, b[0], b[3]-1, b[4])); return d; } var s = '17/12/2017 19:34'; console.log(parseCET(s).toString()); 

However, if the time needs to observe daylight saving (CEST) for the source time stamp, you'll need to account for that.

You can use moment.tz function for parsing time string using a given timezone (eg 'Europe/Madrid' ).

The issue is: what do you mean with CET? If your input has fixed UTC+1 offset (like Central European Time), then you can use RobG's solution. If you have to consider both CET and CEST, I think that the best soution is to use moment.tz .

Here a live code sample:

 const tzGuess = moment.tz.guess() const toTimeZone = (time) => { const format = 'DD/MM/YYYY HH:mm' return moment.tz(time, format, 'Europe/Madrid').tz(tzGuess).format(format) } console.log(toTimeZone('17/12/2017 19:34', tzGuess)) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.4/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.13/moment-timezone-with-data-2012-2022.min.js"></script> 

A great resource about timezone is the timezone tag info page .

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