使用javascript将datetime-local输入的值格式化为user-locale字符串

Format the value of a datetime-local input into a user-locale string using javascript

本文关键字:格式化 user-locale 字符串 javascript datetime-local 输入 使用      更新时间:2023-09-26

如果我在兼容的浏览器(例如Chrome)中使用<input type="datetime-local" />,我从这个输入中得到的值是一个没有时区的ISO时间戳,例如2015-01-31T23:50

然后我想根据用户的区域设置格式化这个时间戳。例如,当我在法国(UTC+1)时,我想得到:31/01/2015 23:50

当我使用以下代码时,时间戳被解释为UTC,我得到这个日期:1/2/2015 00:50 UTC+1

new Date(timestamp).toLocaleDateString(navigator.language, {
  year: "numeric", month: "numeric", day: "numeric", 
  hour: "numeric", minute: "numeric", 
  timeZoneName: "short" 
})

我可以使用new Date().getTimezoneOffset()读取时区偏移量,将其转换为字符串ISO时区,然后将其附加到时间戳,但对我来说似乎相当复杂。

什么将是一个更简单的,纯js或jquery(没有其他库)解决方案格式化时间戳我想要的方式?

你应该绕过所有javascript日期格式化函数,直到最后一刻。

在您的示例中,格式1/01/2015 23:50匹配es-ES或en-GB区域性日期格式,因此您可以使用toLocaleString函数在一次调用中获得所需的格式;)。

问题是,如果你直接用new Date()转换你的日期,它将被解释为ISO-8601格式,这将使事情变得有点困难,所以你应该用一个字符串实例化,作为本地日期。

    var withOffset = new Date(timestamp).toLocaleString('en-GB');
    console.log(withOffset);
    var withoutOffset= new Date(timestamp.replace('T', ' ')).toLocaleString('en-GB');
    console.log(withoutOffset);

第二个版本将把2015-01-31T23:50转换为2015-01-31 23:50,这将被解释为Sat Jan 31 2015 23:50:00 GMT+0100,然后toLocaleString将其转换为您想要的格式。

请注意,这可能无法在浏览器中一致工作,因为您没有使用标准格式将字符串转换为日期(我只在Chrome中测试过)

ECMAScript规范规定:如果String不符合标准格式,则函数可能会退回到任何特定于实现的启发式方法或特定于实现的解析算法。