date-fns: Invalid time value

i use the latest version ( i.e. date-fns v2.0.0 )

if i run this stuff : format(new Date(), 'yyyy-mm-dd')

i got this error:

Starting with v2.0.0-beta.1 date-fns doesn't accept strings as arguments. Please use `parseISO` to parse strings.

so i change to use format(parseISO(new Date()), 'yyyy-mm-dd') but it still not work

is’t a bug ?

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 5
  • Comments: 18 (3 by maintainers)

Most upvoted comments

Kinda irrelevant at this point, but at least maybe I will see my comment if I forget this again. new Date(undefined) returns Invalid Date which, when passed to format, will result in RangeError: Invalid time value. The reason this is somewhat surprising is because I expected new Date(undefined) to be equivalent to new Date() since missing parameters default to undefined. However, if the Date constructor checks arity with something like constructor(...args) { if (args.length > 0) { ... } } I can see how this could cause an issue.

Hi, @kossnocorp, thx reply

this works :

import format from 'date-fns/format'
console.log(format(new Date(), 'yyyy-LL-dd')); // 2019-08-23

so looks like i use the wrong import method

import {format} from 'date-fns/fp'

@hereiscasio arguments order in FP functions is inverted, so you have to:

import format from 'date-fns/format'
// or import { format } from 'date-fns'
console.log(format(new Date(), 'yyyy-LL-dd')); // 2019-08-23

…but:

import format from 'date-fns/fp/format'
// or import { format } from 'date-fns/fp'
console.log(format('yyyy-LL-dd', new Date())); // 2019-08-23

@charles-goode

I had this problem here and I’m looking for a solution.

My import import format from 'date-fns/format';

const isPostEdited =
    post.first_publication_date !== post.last_publication_date;

  let editionDate;
  if (isPostEdited) {
    editionDate = format(
      new Date(post.last_publication_date),
      "'* editado em' dd MMM yyyy', às' H':'m",
      {
        locale: ptBR,
      }
    );
  }

The error that appears: RangeError: Invalid time value

Perhaps add this condition to make sure you aren’t calling new Date(undefined). post.last_publication_date !== undefined

@sujayjaju you can’t pass strings to toDate: https://github.com/date-fns/date-fns/blob/master/src/toDate/index.js#L53-L57

If you want to parse a loose date string, use new Date('2020-05-18 11:11')

I have same isue RangeError: Invalid time value On console.log(format(new Date(user.createdAt), 'yyyy.MM.dd')) i get RangeError

the following helped me: format(parseISO(user.createdAt), 'dd.MM.yyyy; HH:mm')

@jonasgroendahl I used the new Date as suggested by @kossnocorp above