Skip to content
Advertisement

Trying to get first date of current month in html date picker

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;

Advertisement

Answer

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() );

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