简体   繁体   English

Javascript将给定时区中的日期转换为本地日期

[英]Javascript translate date in a given timezone to local date

In Javascript, given a string representing a date like this one:在 Javascript 中,给定一个表示日期的字符串,如下所示:

var dateFromPrague = "2011-10-10T14:48:00"

And knowing above date is a date from a specific localization, like Europe/Prague, how could I get this date translated to the local hour?并且知道上面的日期是来自特定本地化的日期,例如欧洲/布拉格,我怎样才能将此日期转换为当地时间? I know I can create a Date object indicating timezone offset like this:我知道我可以创建一个 Date 对象来指示这样的时区偏移:

var dateFromPrague = new Date("2011-10-10T14:48:00.000+02:00");

Then I could get local date from above date like this:然后我可以像这样从上面的日期获取本地日期:

var dateFromPragueTolocalDate = dateFromPrague.toString();

But Prague offset is not always +02:00 as it depends on DST being applied or not (summer or winter hours).但布拉格偏移并不总是 +02:00,因为它取决于是否应用 DST(夏季或冬季)。 So How could I indicate the right timezone, something like 'Europe/Prague', or achieve this translation some way (returning offset from server is not possible)?那么我怎么能指出正确的时区,比如“欧洲/布拉格”,或者以某种方式实现这种翻译(从服务器返回偏移量是不可能的)?

There isn't currently anything built into JavaScript itself (or the browser platform) that lets you do this, no, you're in the land of libraries.目前还没有内置到JavaScript本身(或浏览器平台)任何东西,可以让你做到这一点,不,你在图书馆的土地是。 In a couple of years you'll probably be able to use Temporal , but it's still at an early stage in the proposals process.几年后,您可能可以使用Temporal ,但它仍处于提案过程的早期阶段。 There's a polyfill linked from the proposal, but the part you'd want to use would probably be the provisionally-named LocalDateTime (not its final name) which is still a work in progress.提案中链接了一个 polyfill,但您想要使用的部分可能是临时命名的LocalDateTime (不是它的最终名称),它仍在进行中。

One library that you can do this with is Moment Timezone .您可以使用的一个库是Moment Timezone That looks like this:看起来像这样:

var a = moment.tz(dateFromPrague, "Europe/Prague");

Live Example:现场示例:

 var dateFromPrague = "2011-10-10T14:48:00"; var a = moment.tz(dateFromPrague, "Europe/Prague"); console.log(a.toDate());
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.31/moment-timezone-with-data.min.js"></script>

You should get the dates in UTC from server and then you can use date.toLocaleDateString() to convert to local date.您应该从服务器获取 UTC 日期,然后您可以使用date.toLocaleDateString()转换为本地日期。 This is the typical approach.这是典型的方法。

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

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