Reputation: 31
Hi I am trying to get first date of current month in HTML date picker.
From <input type="date" id="fdate" value=""/>
To<input type="date" id="tdate" value=""/>
I get today date in id="tdate like this given below but starting date of current month not able to get as I get current date.
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
var today = year + "-" + month + "-" + day;
document.getElementById("tdate").value = today;
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
document.getElementById("tdate").value = firstDay;
Upvotes: 3
Views: 4390
Reputation: 11
Please use this as reference.
This is the code I used:
<html>
<head>
<title>JavaScript Dates</title>
</head>
<body>
<script>
var date = new Date();
document.write("Current Date: " + date );
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
document.write("<br>"+firstDay);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
document.write("<br>"+lastDay);
</script>
</body>
</html>
You can edit this code as suitable to your program.
Upvotes: 0
Reputation: 55210
var date = new Date();
var monthStart = Date.UTC(date.getFullYear(), date.getMonth())
monthStart = toIsoDateString(monthStart);
console.log(monthStart);
var nextMonthStart = Date.UTC(date.getFullYear(), date.getMonth() + 1);
nextMonthStart = toIsoDateString(nextMonthStart);
console.log(nextMonthStart);
function toIsoDateString(utcDate) {
var date = new Date(utcDate);
return date.toISOString().split('T')[0];
}
Upvotes: 1
Reputation: 9273
date
input fields must be in YYYY-MM-DD format. Your code:
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
Will give back a string, e.g. Tue Sep 01 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
, which is not what you want.
You can combine a couple of existing StackOverflow answers to accomplish what you want:
// https://stackoverflow.com/a/23593099/378779
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [year, month, day].join('-');
}
// https://stackoverflow.com/a/13572682/378779
function getFstDayOfMonFnc() {
var date = new Date();
return new Date(date.getFullYear(), date.getMonth(), 1)
}
Assuming fdate
should be the first of the month and tdate
should be today's date:
document.getElementById('fdate').value = formatDate( getFstDayOfMonFnc() );
document.getElementById('tdate').value = formatDate( new Date() );
Upvotes: 1