How to set the calendar to mm-yyyy format

Viewed 386

I want to set the calendar as showing only month and year. As I am using React-Date-Picker npm package. I tried it by using below code

import React, { useState } from 'react';
import DatePicker from 'react-date-picker';
 
function MyApp() {
  const [value, onChange] = useState(new Date());
 
  return (
    <div>
      <DatePicker
        onChange={onChange}
        value={value}
        formatDate="MMMM YYYY"
      />
    </div>
  );
}

In abobe code I also tried with this link and use formatMonth as given in user guide table. but It's not working for me.

How can we solve it?

2 Answers

This can be done natively using the Date class.

function format(date) {
  return [(date.getMonth() + 1).toString().padStart(2, '0'), date.getFullYear()].join('-')
}

console.log(format(new Date()))

You can use Day.js for formatting the date. And update your code as follow:

import dayjs from 'dayjs';

...

<DatePicker
    onChange={onChange}
    value={value}
    formatLongDate={(locale, date) => dayjs(date).format('MM-YYYY')}
/>

...
Related