Skip to content
Advertisement

Jquery Datepicker: date format is not working?

I am trying to display date in dd/mm/yyyy and the value should be store as yyyymmdd in a variable.

dd/mm/yyyy is displayed correct but the value is not storing in format yyyymmdd it is showing as yyyymd

like if I select 02/03/2022 it is storing as 202232 which is incorrect as it has to be store as 20220302.

  var strDateTimeEntry;
   $(function () {
     $("#entrydate").datepicker({
       //date format for displaying
       dateFormat: "dd/mm/yy",
    });
   $("#entrydate").change(function () {
      var date = $(this).datepicker("getDate");
      //date format for storing
       strDateTimeEntry = date.getFullYear() + "" + (date.getMonth() + 1) + "" + date.getDate();
     $("#EntryDateDisplay").text(strDateTimeEntry);
       alert(strDateTimeEntry);
  });
});

Advertisement

Answer

You just need to pad your month and day.

strDateTimeEntry = date.getFullYear() + "" + (date.getMonth() + 1).toString().padStart(2, '0') + "" + date.getDate().toString().padStart(2, '0');

Here’s a fiddle example that takes a Date object and displays output in the required format.

https://jsfiddle.net/udcybs6z/

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement