skip to Main Content

Does any one know how to get only the year using the Textfield type date in react?

 <TextField
                key={"input-year"}
                InputLabelProps={{ shrink: true }}
                required
                fullWidth
                variant="outlined"
                type="date"
                label="Year"
                margin="dense"
                onChange={handleChange}
                value={formValues?.year}
              />

2

Answers


  1. You can do so using JavaScript’s string manipulation functions.In the handleChange function, event.target.value will give you the selected date in "YYYY-MM-DD" format. By using split(‘-‘), you can split this string into an array where the first element is the year.

    import React from 'react';
    import TextField from '@material-ui/core/TextField';
    
    const YourComponent = () => {
      const handleChange = (event) => {
        const selectedYear = event.target.value.split('-')[0];
        console.log(selectedYear);
      };
    
      return (
        <TextField
          key={"input-year"}
          InputLabelProps={{ shrink: true }}
          required
          fullWidth
          variant="outlined"
          type="date"
          label="Year"
          margin="dense"
          onChange={handleChange}
          value={formValues?.year}
        />
      );
    };
    
    export default YourComponent;
    
    Login or Signup to reply.
  2. You can use getFullYear method to get the year from selected event.

    import React from 'react';
    import { TextField } from '@mui/material';
    
    const App = () => {
         const handleChange = (event) => {
            // Extract the year from the selected date
           const selectedDate = event.target.value;
           const selectedYear = new Date(selectedDate).getFullYear();
           console.log(selectedYear);
        };
    
        return (
          <TextField
             key="input-year"
             InputLabelProps={{ shrink: true }}
             required
             fullWidth
             variant="outlined"
             type="date"
             label="Year"
             margin="dense"
             onChange={handleChange}
             value={formValues?.year}
           />
        );
    };
    
    export default App;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search