简体   繁体   中英

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>

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

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 (ie not to assign a Date Object to today and right afterwards making it a string) but do eg 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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM