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.
JavaScript
x
15
15
1
var strDateTimeEntry;
2
$(function () {
3
$("#entrydate").datepicker({
4
//date format for displaying
5
dateFormat: "dd/mm/yy",
6
});
7
$("#entrydate").change(function () {
8
var date = $(this).datepicker("getDate");
9
//date format for storing
10
strDateTimeEntry = date.getFullYear() + "" + (date.getMonth() + 1) + "" + date.getDate();
11
$("#EntryDateDisplay").text(strDateTimeEntry);
12
alert(strDateTimeEntry);
13
});
14
});
15
Advertisement
Answer
You just need to pad your month and day.
JavaScript
1
2
1
strDateTimeEntry = date.getFullYear() + "" + (date.getMonth() + 1).toString().padStart(2, '0') + "" + date.getDate().toString().padStart(2, '0');
2
Here’s a fiddle example that takes a Date object and displays output in the required format.