skip to Main Content

I am trying to implement date field similar to this page with date format of yyyy/mm/dd in react.

This is what i have tried

const [date_of_birth,setDateofBirth] = useState("");
const handleChangeDOB = (e) => {
    let value = e.target.value;
    value = value.replace(/D/g, "");
    if(value.length >= 6){
      value = `${value.slice(0, 4)}/${value.slice(4, 6)}/${value.slice(6)}`;
    }
    else if(value.length >= 4){
      value = `${value.slice(0, 4)}/${value.slice(4)}`;
    }
    setDateofBirth(value);
}

<input type="text" maxLength={10} value={date_of_birth} onChange={handleChangeDOB} placeholder="yyyy/mm/dd"/>

When ever i try to delete it does not work correctly. If delete from in between then there can be two slash. What else I have to do to make it work ?

3

Answers


  1. Is this solution enough: https://codesandbox.io/s/strange-engelbart-0pcpep?file=/src/App.js

    Im using the react-input-mask to handle the masking logic.

          <InputMask
            mask="9999/99/99"
            maskChar=""
            value={date_of_birth}
            onChange={handleChangeDOB}
            placeholder="yyyy/mm/dd"
          />
    

    The docs for the component are here: https://www.npmjs.com/package/react-input-mask

    Login or Signup to reply.
  2. Well, Here is what you can do.
    This is for checking value function.

    const checkValue = (str, max) => {
          if (str.charAt(0) !== '0' || str == '00') {
            var num = parseInt(str);
            if (isNaN(num) || num <= 0 || num > max) num = 1;
            str = num > parseInt(max.toString().charAt(0)) 
                   && num.toString().length == 1 ? '0' + num : num.toString();
          };
          return str;
        };
    

    And here is the event listener for your input.

    const handleChangeDOB = (e) => {
      let value = e.target.value;
      if (/D/$/.test(value)) value = value.substr(0, value.length - 3);
      let values = value.split("/").map(function (v) {
        return v.replace(/D/g, "");
      });
      if (values[0]) values[0] = checkValue(values[0], 12);
      if (values[1]) values[1] = checkValue(values[1], 31);
      let output = values.map(function (v, i) {
        return v.length == 2 && i < 2 ? v + " / " : v;
      });
      setDateofBirth(output.join("").substr(0, 14));
    };
    

    I hope this will work for you.

    Login or Signup to reply.
  3. -There are different ways to convert date to yyyy / mm / dd format in React.One way is to use the date - fns library, which allows you to customize your own format.For example:
    
      import {
        format
      } from 'date-fns';
    console.log(format(new Date(), 'yyyy/MM/dd kk:mm:ss'))
    
      
    -Another way is to use the Intl.DateTimeFormat object, which formats a date according to the locale and options you specify.For example:
    
      const today = Date.now();
    console.log(new Intl.DateTimeFormat('en-US', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    }).format(today));
    
    
    -You can also use the moment library, which provides a simple way to format dates.For example:
    
      import moment from 'moment';
    console.log(moment(yourDate).format("YYYY/MM/DD kk:mm:ss"));
    I hope this helps you with your code conversion.😊
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search