0

我正在尝试设置具有 ISOString 格式的日期,但毫秒应设置为两位数。

如果 ISOString 返回 2021-11-02T05:49:12.704ZI 希望它是 2021-11-02T05:49:12.70Z (毫秒四舍五入到两个位置)

这就是我想要做的。

let startdate = new Date();
console.log(startdate.getMilliseconds()); //just to check
let d = startdate.toString().replace(microsecond=Math.round(startdate.microsecond, 2))  
console.log(d) //format is different
startdate =  startdate.toISOString() //this is different than d
console.log(startdate)

输出为

961
Tue Nov 02 2021 05:50:46 GMT+0000 (Coordinated Universal Time)
2021-11-02T05:50:46.961Z

任何人都可以帮忙吗?

4

3 回答 3

2

解析出秒和毫秒并将其替换为固定精度数

const now = new Date()
const formatted = now
  .toISOString()
  .replace(/\d{2}\.\d{3,}(?=Z$)/, num =>
    Number(num).toFixed(2).padStart(5, "0"))
  
console.log(formatted)

于 2021-11-02T06:12:46.077 回答
1

舍入毫秒部分并替换尾随0Z

new Date(Math.round(new Date().getTime() / 10) * 10).toISOString().replace('0Z', 'Z')

如果是简单的截断,使用Math.floor或正则表达式替换

new Date(Math.floor(new Date().getTime() / 10) * 10).toISOString().replace('0Z', 'Z')
new Date().toISOString().replace(/\dZ$/, 'Z')
于 2021-11-02T06:07:23.973 回答
0

如果您对截断而不是四舍五入感到满意,这很有趣,虽然相当神秘:

> d = new Date().toISOString()
'2021-11-02T06:00:01.601Z'
> d.replace(/(\d\d\.\d\d)\d/, "$1",)
'2021-11-02T06:00:01.60Z'

它依赖于toISOString始终在小数点之后产生 3 位数字。在这里您可以使用replace只保留前两位数字。

这是另一个运行:

> d = new Date().toISOString()
'2021-11-02T06:02:25.420Z'
> d.replace(/(\d\d\.\d\d)\d/, "$1",)
'2021-11-02T06:02:25.42Z'

正如我所提到的,它会截断而不是取整,因此您可能会注意到以下情况:

> d = new Date().toISOString()
'2021-11-02T06:03:53.157Z'
> d.replace(/(\d\d\.\d\d)\d/, "$1",)
'2021-11-02T06:03:53.15Z'

现在如果你真的想要四舍五入,试试这个:

> d.replace(/(\d\d\.\d\d\d)/, s=>Number(s).toFixed(2))
'2021-11-02T06:03:53.16Z'

那个有在实际数字上做工作的优势。但它会在 0 到 9 秒之间失败,因此借用 Phil 的正确答案,请使用padStart确保将前导零保留几秒钟:

> d = '2021-11-02T06:22:03.266Z'
> d.replace(/(\d\d\.\d\d\d)/, s=>Number(s).toFixed(2).padStart(5, '0'))
'2021-11-02T06:22:03.27Z'

菲尔的正则表达式也更通用,所以接受这个答案。

于 2021-11-02T06:03:04.703 回答