如何在 JS 中将 toLocaleString() 方法的结果转换为秒数

How to convert the result from toLocaleString() method to seconds in JS

var d = new Date("sep 01, 2020 01:59:59");
var c = d.toLocaleString('de-DE', {timeZone: 'CET'});
console.log(c); // 31.8.2020, 17:59:59

我需要将变量 c 转换为毫秒,就像 getTime() 方法对 Date 对象所做的那样。如何做到这一点?

尽可能远离 localeStrings

它们丑陋且难以编程。老实说,对底层日期对象进行所有处理,并使用 ISO 日期字符串存储所有文本。无论如何,如果有人用枪指着你强迫你接收一个 localeString,让 Javascript 为你解释如下。

var d = new Date("sep 01, 2020 01:59:59");
var c = d.toLocaleString('de-DE', {timeZone: 'CET'});

var sensibleFormat = new Date(c)
var milliseconds = sensibleFormat.getTime()
console.log(milliseconds)

根据您上面的说明(“我必须将时区更改为 CET”),您提到 CET 是因为您想从 CET 中定义的某个固定时间开始计算毫秒数吗?

如果您指定一个数字答案正确的示例,您的问题会更容易回答。

不要这样做

OP 的尝试存在很多问题,首先是 new Date("sep 01, 2020 01:59:59"):

  1. ECMA-262 不支持该格式,因此解析取决于实现,可能会或可能不会按预期解析
  2. 即使解析正确,也会假定主机系统偏移量,因此对于具有不同偏移量的每个系统,它代表不同的时间时刻

另见 Why does Date.parse give incorrect results?

d.toLocaleString('de-DE', {timeZone: 'CET'}) 的问题:

  1. 未指定确切的输出格式,因此实现可以自由地将语言“de-DE”转换为他们认为匹配的任何格式
  2. 无论生成什么格式,生成它的实现都不需要对其进行解析,更不用说其他实现了。例如。给定 new Date('31.8.2020, 17:59:59') Safari 和 Firefox return 一个无效日期
  3. 时区可能未包含在字符串中,因此会出现与上述 #2 相同的问题。

改为这样做

一个合理的方法是对字符串使用一些其他解析器并关联所需的时区(库可以对此提供很大帮助,可以将其添加到字符串或将其指定为选项)。这应该会生成一个合适的 Date 并提供一种获取时间值的方法,该时间值是毫秒,因此可以通过除以 1000 转换为秒。

在没有图书馆的情况下做到这一点的唯一方法就是搞乱 Intl.DateTimeFormat to work out what the offset should be, then manually apply it (per this anwer)。使用像 Luxon 这样的库要简单得多:

let DateTime = luxon.DateTime;

// Timestamp to parse
let s = 'sep 01, 2020 01:59:59';
// Format of input timestamp
let fIn = 'MMM dd, yyyy HH:mm:ss';
// Location to use to determine offset when parsing
let loc = 'Europe/Paris';
let d = DateTime.fromFormat(s, fIn, {zone: loc});
// Show date using Luxon default format
console.log(d); // "2020-09-01T01:59:59.000+02:00"

// Show date in set format
let fOut = 'dd.MM.yyyy, HH:mm:ss ZZ'; 
console.log(d.toFormat(fOut)); // 01.09.2020, 01:59:59 +02:00

// UNIX timestamp in seconds
console.log(d.toFormat('X'));  // 1598918399
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/1.24.1/luxon.min.js"></script>

你可以用其他库做同样的事情,Luxon 只是一个方便的例子。请注意,对于 Luxon,一旦某个位置与对象相关联,它就会继续将该位置用于偏移量和时区数据,这可能很方便也可能很烦人,具体取决于您要执行的操作。