简体   繁体   English

CET时区中的日期到用户的时区

[英]Date in CET timezone to user's timezone

I have a list of list of string dates like this: '17/12/2017 19:34' . 我有一个像这样的字符串日期列表: '17/12/2017 19:34' They are CET dates. 他们是CET时间。

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? 但是我moment该如何说起初的日期是英语CET呢?

Thanks! 谢谢!

Without moment.js, parse the string to a Date, treating it as UTC, then adjust for the CET offset (+0100). 如果没有moment.js,则将字符串解析为日期,将其视为UTC,然后调整CET偏移量(+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. 但是,如果时间需要遵守源时间戳的夏令时(CEST),则需要考虑这一点。

You can use moment.tz function for parsing time string using a given timezone (eg 'Europe/Madrid' ). 您可以使用moment.tz函数来解析给定时区的时间字符串(例如'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. 如果您的输入具有固定的UTC + 1偏移量(如中欧时间),则可以使用RobG的解决方案。 If you have to consider both CET and CEST, I think that the best soution is to use moment.tz . 如果必须同时考虑CET和CEST,我认为最好的选择是使用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 . 有关时区的重要资源是时区标签信息页面

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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