0

I want to get the same date format when clicking on "Tomorrow" button. Currently it showing two different output on clicks. If anybody could provide the solution? Below is the JS code.

 var today = new Date(),
    dd = today.getDate(),
    mm = today.getMonth()+1,
    yyyy = today.getFullYear(),
    nextDate = new Date(today.getTime() + (24 * 60 * 60 * 1000)),
    tomorrow = nextDate.toDateString();

if(dd<10){
    dd='0'+dd
}
if(mm<10){
    mm='0'+mm
} 
today = dd+'/'+mm+'/'+yyyy;

addEventListener("load", function(){
    dateInput = document.getElementById('dateID');
    dateInput.value = "";
}, false);

function currentDate(){
    dateInput.value = today;
}
function tomorrowDate(){
    dateInput.value = tomorrow;
}

/******************************

<div class="wrapper">
    <input type="text" id="dateID" /><br />
    <input type="button" value="Today" onclick="currentDate();" />
    <input type="button" value="Tomorrow" onClick="tomorrowDate();" />
</div>

2 Answers 2

2

Try this code

function currentdate()
{

            var currentDate = new Date()
            var day = (currentDate.getDate()<10 ? "0" : "") + currentDate.getDate()
            var month = (currentDate.getMonth()<9 ? "0" : "") + (currentDate.getMonth()+1)
            var year =  currentDate.getFullYear()
            var todayDate =  month +"/" +day + "/" + year ;
            return todayDate;
}
Sign up to request clarification or add additional context in comments.

Comments

0

If you just want similar date format output you could change this line today = dd+'/'+mm+'/'+yyyy to today = today.toDateString(); or if you want it in the dd/mm/yyyy format:

I would suggest not to use global variables for this and would not mix up types (i.e. not to assign a Date Object to today and right afterwards making it a string) but do e.g. something like this:

    addEventListener("load", function(){
    dateInput = document.getElementById('dateID');
    dateInput.value = "";
}, false);

function formatDate(dt) {
    var dd = dt.getDate();
    var mm = dt.getMonth() + 1;
    var yyyy = dt.getFullYear();
    return dd + "/" + mm + "/" + yyyy;
}

function currentDate(){
    dateInput.value = formatDate(new Date());
}
function tomorrowDate(){
    dateInput.value = formatDate(new Date(new Date().getTime() + 24 * 60 * 60 * 1000));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.