简体   繁体   中英

How to format date in react-calendar?

I check the document and I found the formatLongDate and I try this but it's not formatting date.

I want my date like this YYYY-MMM-dd but the calendar gave me like this Wed Apr 07 2021 00:00:00 GMT+0000 How can I format this date? I'm really new to React JS. Thank you.

import React, {useState} from 'react';
import Calendar from "react-calendar";
import 'react-calendar/dist/Calendar.css'


const comp = () => {

    const [date, setDate] = useState(new Date());

    return (
        <div>
            <Calendar
                onChange={setDate}
                value={date}
                maxDate={new Date()}
                formatLongDate={(locale, date) => formatDate(date, 'YYYY-MMM-dd')}
            />

        </div>
    );

};

export default comp;

You can use dayjs to format date. You can see the code below

import React, {useState} from 'react';
import Calendar from "react-calendar";
import 'react-calendar/dist/Calendar.css';
import dayjs from 'dayjs';

export default function App() {
  const [date, setDate] = useState(new Date());
  return (
      <div>
          <Calendar
              onChange={setDate}
              value={date}
              maxDate={new Date()}
              formatDay ={(locale, date) => dayjs(date).format('YYYY-MM-DD')}
          />
      </div>
  );
}

here is codesandbox .

Another more efficient way to achieve your goal without introducing any other dependency while using Int.DateTimeFormat follows.

Visit for more details https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat

import React, {useState} from 'react';
import Calendar from "react-calendar";
import 'react-calendar/dist/Calendar.css'


const comp = () => {

    const [date, setDate] = useState(new Date());
    const locale = 'fr-CA'; 
    return (
        <div>
            <Calendar
                onChange={setDate}
                value={date}
                maxDate={new Date()}
                formatDay ={
                  (date) => new Intl.DateTimeFormat(
                    locale, 
                    {
                      year: "numeric", 
                      month: "2-digit", 
                      day: "2-digit"
                    }).format(date)
                  }
                 />
        </div>
    );
};

export default comp;

This will help you, if the number of dependencies is a factor for your application ( Application Load Time ).

You can view it live here https://codesandbox.io/s/adoring-franklin-zvmti

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