简体   繁体   中英

How to convert to date-fns?

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? I converted like this:

setStartDate(getUnixTime(new Date(value)))

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'));

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)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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