4

Here is my below custom component for datepicker with yyyy format

 return (
      <DatePickerWrapper disable={disable} >
        <DatePicker
          name={this.props.name}
          selected={this.state.startDate}
          onChange={this.handleChange}
          onBlur={this.handleBlur}
          showYearPicker
          dateFormat={"yyyy"}
        />
      </DatePickerWrapper>
    );

I am still able to see it mm/dd/yyyy format

Abhishek Konnur
  • 503
  • 1
  • 9
  • 33

3 Answers3

0

if i understand correctly You want it to be displayed for only a year, but what Displayed as "Thu Jan 01 1970 07:00:01 GMT+0700". You need to use .getFullYear() in onChange , this is the method I tried and it works.

    import { useState } from "react";
    import DatePicker from "react-datepicker";
    
    const [savedate, setSavedate] = useState();
    
    const <your component> = () => {
    
      return() {
            <DatePicker
               id="DatePicker"
               type="string"
               className="text-primary text-center"
               selected={birthYear}
               onChange={(date) => setSavedate(date.getFullYear())}
               showYearPicker
               dateFormat="yyyy"
               yearItemNumber={9}
               required
            />
      }
    }
0

There is a library called react-datetime.We can pick only year using this library. Install the library using this command:npm i react-datetime

Reference:https://www.npmjs.com/package/react-datetime

  • This library is rather outdated. I'd suggest using something more recent of accepting year as a textbox with validation instead. – Andrii Oct 14 '22 at 22:36
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/32915278) – Vojin Purić Oct 15 '22 at 07:53
  • @Andrii & @Vojin Purić thank you for all your valuable comments. Yes, the react-year-picker library is outdated. We can use `react-datetime` library with dateFormat="YYYY" in HTML tag. Like this, – Rekha Rajasekaran Oct 17 '22 at 12:10
0

I solved it in this way. I used 'react-datepicker' v4.11.0.

import moment from 'moment';
import React, { useState } from 'react';
import DatePicker from 'react-datepicker';

const DatePickerComponent = () => {
  const [startDate, setStartDate] = useState(1659312000000);

  const year = moment(startDate).format('yyyy');

  return (
    <div>
      <h1>Date Picker</h1>
      <p>Selected year: {year}</p>
      <DatePicker
        selected={startDate}
        onChange={(date) => setStartDate(date)}
        showYearPicker
        dateFormat="yyyy"
      />
    </div>
  );
};

export default DatePickerComponent;

Find a working link here: https://stackblitz.com/edit/react-tfzvsm?file=src%2Fdate-picker.jsx

Shubham Yerawar
  • 660
  • 5
  • 9