Search code examples
javascriptdatedate-fns

Invalid time value when using date-fns package


There's a particular date "2025-08-01" which is throwing a RangeError: Invalid time value when being used in the date-fns package. Any clue around why this might be happening?

const dfs = require('date-fns');
new Date("2025-08-01") // works
dfs.format("2025-08-01", 'MM-yyyy'); // throws RangeError: Invalid time value

https://runkit.com/embed/ub1wub4pnkjk


Solution

  • You are passing a string to the format function in the date-fns package, while it expects a Date object as its first argument. To fix the error, you should create a Date object and pass it to the format function like this:

    const dfs = require('date-fns');
    const date = new Date("2025-08-01"); // Create a Date object
    console.log(dfs.format(date, 'MM-yyyy')); // Format the Date object
    

    Reference: date-fns docs