user2265582
user2265582

Reputation:

How to format date output using Javascript

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>

Upvotes: 0

Views: 3036

Answers (2)

Mariraj Sankar
Mariraj Sankar

Reputation: 69

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;
}

Upvotes: 2

Mallard
Mallard

Reputation: 308

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

Upvotes: 0

Related Questions