Reputation: 2689
I'd like to display the date of the first day of the selected month but the format of date doesn't showing me the right format.
I'd like to show it like this 01/11/2017 but it is displayed like this
Wed Nov 01 2017 00:00:00 GMT+0100 (CET)
Select a Date: <input type="date" id="theDate" onmouseout="getTheDays()"/>
<p>First Day of the Month: <label id="fday"></label></p>
<p>Last Day of the Month: <label id="lday"></label></p>
<script>
function getTheDays() {
var dt = new Date($('#theDate').val());
// GET THE MONTH AND YEAR OF THE SELECTED DATE.
var month = dt.getMonth(),
year = dt.getFullYear();
// GET THE FIRST AND LAST DATE OF THE MONTH.
var FirstDay = new Date(year, month, 1);
var LastDay = new Date(year, month + 1, 0);
// FINALLY, GET THE DAY.
var weekday = new Array();
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
if (typeof weekday[FirstDay.getDay()] != 'undefined') { // CHECK FOR 'undefined'.
$('#fday').html(FirstDay.toString('dd-MM-yy'));
}
else {
$('#fday').text('');
$('#lday').text('');
}
}
</script>
Upvotes: 0
Views: 30
Reputation: 3698
I share with you our toShortDate
function, here you are:
function toShortDate(date) {
if (!date) {
return '--/--/--';
}
var d = new Date(Date.parse(date)),
days = d.getDate(),
month = (d.getMonth() + 1),
finalDays = days < 10 ? '0' + days : '' + days,
finalMonth = month < 10 ? '0' + month : '' + month;
return finalDays +
"/" + finalMonth +
"/" + d.getFullYear().toString().substr(2, 2);
}
This function has been working in production for a while now and it works perfectly. Good luck.
Upvotes: 2