点击“明天”按钮,我想获得相同的日期格式。目前它显示两个不同的点击输出。如果有人能提供解决方案?下面是JS代码。
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>
答案 0 :(得分:2)
试试此代码
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;
}
答案 1 :(得分:0)
如果您只想要类似的日期格式输出,可以将此行today = dd+'/'+mm+'/'+yyyy
更改为today = today.toDateString();
,或者如果您想要它以dd / mm / yyyy格式:
我建议不要为此使用全局变量,也不要混淆类型(即不要将Date
对象分配给today
,然后再将其作为字符串),但请执行以下操作:像这样的东西:
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));
}