简体   繁体   English

如何在JavaScript中将浮点值转换为日期时间格式

[英]How to convert floating point value to date time format in javascript

I get a time difference from mongodb: 我从mongodb得到了时差:

9.266666666666667

and rounded it off to two decimal places: 并四舍五入到小数点后两位:

9.27

Now i want to format it to 00:00 time format. 现在我想将其格式化为00:00时间格式。 And i tried to format this using moment js: 我试图使用时刻js格式化该格式:

moment(9.27).format('HH:mm')

But it returns: 但它返回:

08:00 

which is wrong. 这是错误的。

It should be: 它应该是:

09:16

Anyone have ideas? 有人有想法吗? Thank you. 谢谢。

我从这篇文章中找到了答案: 如何将十进制小时值转换为hh:mm:ss

var time_formatted = moment().startOf('day').add(parseFloat(9.266666666666667), "hours").format("hh:mm");

If 9.27 really needs to be translated into 09:27, you can parse it as a glued hour/minute: console.log(moment(9.27, "hhmm").format("HH:mm")) // 09:27 如果确实需要将9.27转换为09:27,则可以将其解析为固定的小时/分钟: console.log(moment(9.27, "hhmm").format("HH:mm")) // 09:27

However, as others have pointed out, note that 9.27 hours is NOT 9h 27min. 但是,正如其他人指出的那样,请注意,9.27小时不是9小时27分钟。

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

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