简体   繁体   English

date-fns "RangeError: 时间值无效"

[英]date-fns "RangeError: Invalid time value"

I am trying to convert 18:00:00.000 to 24H (18:00) and 12H (6PM) formats using date-fns.我正在尝试使用 date-fns 将 18:00:00.000 转换为 24H (18:00) 和 12H (6PM) 格式。 However, the input value of 18:00:00.000 gives a "RangeError: invalid time value".但是,18:00:00.000 的输入值给出了“RangeError: invalid time value”。

My code我的代码

dateFns.format(new Date(18:00:00.000), 'H:mm')

I have no problem if I pass the time in the dateTime format such as 2022-01-04T11:00:00.000Z but I just need the time (hours and minutes).如果我以 dateTime 格式(例如 2022-01-04T11:00:00.000Z)传递时间,我没有问题,但我只需要时间(小时和分钟)。

Your code is failing because new Date() requires a valid date time string to create a new date object.您的代码失败,因为new Date()需要有效的日期时间字符串来创建新日期 object。 To fix this, simply formulate a current date string and attach the timestamp you require and pass it to the new Date() method.要解决这个问题,只需制定一个当前日期字符串并附加您需要的时间戳并将其传递给new Date()方法。 Then you can pass the date object to the format method to get the desired output.然后可以将日期object传递给format方法得到想要的output。

Refer to this chart to format your dates as per your requirement.请参阅图表以根据您的要求格式化您的日期。

 const now = dateFns.format(new Date(), 'YYYY-MM-DD'); const custTime = '18:00:00.000'; const custDt = new Date(`${now} ${custTime}`); console.log(dateFns.format(custDt, 'h:mm A'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/2.0.0-alpha0/date_fns.min.js" integrity="sha512-0kon+2zxkK5yhflwFqaTaIhLVDKGVH0YH/jm8P8Bab/4EOgC/n7gWyy7WE4EXrfPOVDeNdaebiAng0nsfeFd9A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

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

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