Home > Software design >  How to convert to date-fns?
How to convert to date-fns?

Time:11-10

I have following moment expression:

<DialogContent>
  {startDate ? (
    <DateTimePicker
      value={startDate}
      onChange={(value: any) =>
        setStartDate(moment(value).format())

I would like to convert to date-fns format, but it fails, it is always 1970 something, why?

setStartDate(getUnixTime(new Date(value)))

CodePudding user response:

You can import format function from date-fns and use it:

import { format } from 'date-fns';

// Pass desired format as a second parameter
setStartDate(format(value, 'yyyy-MM-dd'));

CodePudding user response:

moment(value).format() return a ISO 8601 date string, look like: 2021-11-10T10:19:09 09:00. Then, I guess the setStartDate function require a date string with ISO 8601 format.

The goal is using date-fns to create a string as the result of moment.format.

To do that, you need to create a date object. If it works with moment(value) syntax, mean value is a millisecond timestamp number (1636507295498) or a formal date string (2021-11-10). Then you can create a date object by Date constructor:

new Date(value);

Now, you can use formatISO to create the required date string:

formatISO(dateObject);

The final look will be like this:

setStartDate(formatISO(new Date(value)))
  • Related