简体   繁体   English

date-fns格式无法正确格式化microSeconds?

[英]date-fns format does not format properly microSeconds?

I am using the following script in order convert microSeconds in hh:mm using date-fns but I get the wrong formatting: 我正在使用以下脚本,以便使用date-fns在hh:mm中转换microSeconds,但格式错误:

const microSeconds = 100000000 format(addMilliseconds(new Date(0), microSeconds / 1000), 'hh:mm')}

for example in this case I would need to get '00:01' but instead I get 01:01 例如,在这种情况下,我需要获取“ 00:01”,但我需要获取01:01

Any idea how to fix it? 知道如何解决吗?

Runnable code https://stackblitz.com/edit/date-fns-playground-cdgduf 可运行的代码https://stackblitz.com/edit/date-fns-playground-cdgduf

It's because date-fns format function relies on locales. 这是因为date-fns格式函数依赖于语言环境。 Format's docs contains information (under table with accepted tokens): 格式的文档包含信息(在带有接受标记的表下方):

The result may vary by locale. 结果可能因地区而异。

You could subtract timezone offset: 您可以减去时区偏移量:

const d = new Date(0);
const formatedValue = format(
   addMilliseconds(new Date(0 + d.getTimezoneOffset()*1000*60), microSeconds / 1000), 'HH:mm')

Change also date format to HH:mm , because hh is between 01 and 12 将日期格式也更改为HH:mm ,因为hh在01到12之间

According to this example: 根据此示例:

import { format } from 'date-fns';
const formatedValue = format(0, 'hh:mm')
// output: 01:00

You should not use date-fns to just convert a duration into a human-readable string since it always depends on timezones. 您不应该使用date-fns将持续时间转换为人类可读的string因为它始终取决于时区。 You should implement your own format function since it's basic dividing and multiplying. 您应该实现自己的格式函数,因为它是基本的除法和乘法。

Working example => https://stackblitz.com/edit/date-fns-playground-whz5tg?file=app.ts 工作示例=> https://stackblitz.com/edit/date-fns-playground-whz5tg?file=app.ts

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

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