简体   繁体   English

Javascript - 显示日期时间并忽略语言环境/时区

[英]Javascript - Display date time and ignore locale/timezone

I am having a bit of a nightmare working with a CMS that saves datetimes without timezones.我在使用 CMS 时遇到了一些噩梦,它可以在没有时区的情况下保存日期时间。 For a wide variety of infrastructure reasons I am unable to adjust core files , I can only adjust some of the javascript of the CMS field itself, and not include external libraries (or the dayjs UTC plugin).由于各种基础设施原因我无法调整核心文件,我只能调整CMS领域本身的一些javascript,而不包括外部库(或dayjs UTC插件)。

How it currently works:目前的工作方式:

  1. CMS Saves datetime string like so: 2020-10-29 05:00 which is missing the timezone CMS 像这样保存日期时间字符串: 2020-10-29 05:00缺少时区
  2. When reloading, the dayjs parses the string 2020-10-29 05:00 as UTC and changes the time based on the browser locale.重新加载时,dayjs 将字符串2020-10-29 05:00解析为UTC并根据浏览器区域设置更改时间。
  3. If you are using a browser that it not UTC, the time displayed will not correspond to the saved string如果您使用的浏览器不是 UTC,则显示的时间将与保存的字符串不符

My hacky idea:我的想法:

  1. When loading the string, get the browser's timezone加载字符串时,获取浏览器的时区
  2. Modify the string 2020-10-29 05:00 to include the browser's timezone, or offset the date object so that when it is parsed as 'local', it will display correctly修改字符串2020-10-29 05:00以包含浏览器的时区,或偏移日期对象,以便当它被解析为'local'时,它会正确显示

My initial thought was just to add/subtract the offset before displaying but it still didn't seem to work (I think due to getTimezoneOffset not adjusting for daylight savings?):我最初的想法只是在显示之前添加/减去偏移量,但它似乎仍然不起作用(我认为是因为 getTimezoneOffset 没有针对夏令时进行调整?):

let date = new Date('2020-10-29 05:00')
console.log(new Date(date.setMinutes(date.getMinutes() + new Date().getTimezoneOffset())))

I suppose an alternate form of this question is: Is there a way to parse a UTC datetime string as though it were local?我想这个问题的另一种形式是:有没有办法解析 UTC 日期时间字符串,就好像它是本地的一样?

If the string is UTC, you should parse it as UTC and then do everything in UTC.如果字符串是 UTC,您应该将其解析为 UTC,然后在 UTC 中执行所有操作。 I think the easiest way is to parse the string as UTC with your own function or library.我认为最简单的方法是使用您自己的函数或库将字符串解析为 UTC。

Also, given:另外,给定:

new Date('2020-10-29 05:00')

some browsers will return an invalid date (they treat it as a malformed version of the supported format YYYY-MM-DDTHH:mm:ss).某些浏览器将返回无效日期(他们将其视为支持格式YYYY-MM-DDTHH:mm:ss 的畸形版本)。

Generally, using the built–in parser is strongly discouraged because of browser inconsistencies.通常,由于浏览器不一致,强烈建议不要使用内置解析器。 Also, messing with timezone offsets can also lead to difficult to find issues (like when applying the offset causes the date to cross a DST boundary).此外,弄乱时区偏移量也可能导致难以找到问题(例如当应用偏移量导致日期跨越 DST 边界时)。

A simple function to do the job:一个简单的功能来完成这项工作:

 function parseAsUTC(s) { let [y, m, d, H, M] = s.split(/\\D/); return new Date(Date.UTC(y, m-1, d, H, M)); } let s = '2020-10-29 05:00'; console.log(parseAsUTC(s));

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

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