如果我使用 <input type="datetime-local" />
在兼容的浏览器(例如 Chrome)中,我从这个输入中得到的值是一个没有时区的 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 中测试过)
The ECMAScript specification states: If the String does not conform to the standard format the function may fall back to any implementation–specific heuristics or implementation–specific parsing algorithm.
关于javascript - 使用 javascript 将日期时间本地输入的值格式化为用户区域设置字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30440698/