Home > database >  date-fns "RangeError: Invalid time value"
date-fns "RangeError: Invalid time value"

Time:01-16

I am trying to convert 18:00:00.000 to 24H (18:00) and 12H (6PM) formats using date-fns. However, the input value of 18:00:00.000 gives a "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).

CodePudding user response:

Your code is failing because new Date() requires a valid date time string to create a 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. Then you can pass the date object to the format method to get the desired 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>

  •  Tags:  
  • Related