Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 890
user8159589 Avatar asked Jan 29 '26 06:01

user8159589


1 Answers

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

like image 102
Manifest Man Avatar answered Feb 01 '26 00:02

Manifest Man