want to convert date format 24/05/2021 to 24/May/2021 on using jQuery / JavaScript

Viewed 274

I have a date 24/05/2021, I want to convert its date format to 24/May/2021 using Javascript or jquery as user leaves textbox, my client don't want to use date picker, he just want to type dates straight and auto convert date as he leaves the textbox, like he does in excel.

I find many ways but got nothing, I know how to do it server side but it has to be done at client side.

3 Answers

As you said that client don't want to use date picker, you need to define the format that user will input.

You can split every segment and then format the month, then put the value in the input element's value on DOM.

As for the example below, I assume that the user uses / as the separator for the input.

function formatDate(val){
  var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
  
  var parts = val.split('/');
  var d = parts[0];
  var y = parts[2];
  var m = months[parseInt(parts[1], 10) - 1];
  
  var inp = document.querySelector('#inp');
  if(/[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}/.test(val)){
    inp.value = `${d}/${m}/${y}`;
  } else inp.value = "";
}
<input type="text" id="inp" required pattern="[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}" onchange="formatDate(this.value)"/>

you can use regex to check if the date inputted is correct or not, if it is correct then you can change its format, otherwise you can show error. Here is the code:

const month = ["January","February","March","April","May","une","July","August","September","October","November","December"];

const dateregex = /^[0-3]?[0-9]\/[0-1]?[0-9]\/[0-9][0-9][0-9][0-9]/

class DateField {
    constructor(id) {
    this.elem = document.getElementById(id);
    this.elemInp = this.elem.children[1];
    this.elemError = this.elem.children[0];
    this.date = null;
    this.elemInp.addEventListener('blur', () => {
        console.log(dateregex.test(this.elemInp.value), dateregex, this.elemInp.value);
        if (!dateregex.test(this.elemInp.value)) {
        this.showError();
        this.date = null;
        return;
      }
      var datesplits = this.elemInp.value.split('/');
      
        this.date = new Date();
      this.date.setYear(parseInt(datesplits[2],10));
      this.date.setDate(parseInt(datesplits[0],10));
      this.date.setMonth(parseInt(datesplits[1],10) - 1);
        
      var newDateString = this.date.getDate() + '/' + month[this.date.getMonth()] + '/' + this.date.getFullYear();
      this.elemInp.value = newDateString;
      this.removeError();
      
    });
    this.elemInp.addEventListener('focus', () => {
        if (this.date !== null && !isNaN(this.date.getTime())) {
        var newDateString = this.date.getDate() + '/' + (this.date.getMonth() + 1) + '/' + this.date.getFullYear();
        this.elemInp.value = newDateString;
      }
    });
  }
  
  showError() {
    this.elemError.innerText = "date is invalid";
  }
  
  removeError() {
    this.elemError.innerText = "";
  }
}

var d1 = new DateField("dateContainer");
<html>
  <head>
    <title>try js</title>
  </head>
  <body>

    <div id="dateContainer">
      <p style="color: red;"></p>
      <input type="text" id="date" />
    </div>

  </body>
</html>

You can split the string on "/" and then with the second array element you make an array with the months like this:

const monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];

Then you split your string on "/" and get a date like:

const split = document.querySelector("#input").split("/");

const date = new Date(`${split[1]}/${split[0]}/${split[2]}`);

And finally:

const month = monthNames[date.getMonth()];

The HTML is gonna be something like this:

<input type="text" id="input" required onchange="formatDate(this.value)"/>
Related