我想使用JavaScript显示昨天的日期。为此,我使用如下代码:
<p id="demo"></p>
<script type=text/javascript>
var d = new Date();
d.setDate(d.getDate() - 1);
document.getElementById("demo").innerHTML = d;
</script>
虽然有效,但会以完整的格式显示日期:
Sun May 01 2016 2016 11:31:53 GMT-0700(Pacific Daylight Time)
我想只显示这样的日期和日期格式:
2016年5月1日星期日
有没有解决方案?
答案 0 :(得分:2)
如果您可以灵活使用外部库,则可以使用moment.js。
document.write(moment().add(-1, "days").format("ddd MMM DD YYYY"))
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
&#13;
答案 1 :(得分:1)
var d = new Date();
d.setDate(d.getDate() - 1);
var weekday = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var dayName = weekday[d.getDay()];
var month = months[d.getMonth() ];
var day = d.getDate();
var year = d.getFullYear();
month = month < 10 ? "0" + month : month;
day = day < 10 ? "0" + day : day;
var output = dayName + ' ' + month + ' ' + day + ' ' + year;
答案 2 :(得分:1)
getDay()
返回0-6。getMonth()
返回0-11,因此请为正确的位置创建自定义数组名称。然后您可以调用它..
<p id="demo"></p>
<script type=text/javascript>
var d = new Date();
var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var month = ["January", "February", "March","April", "May", "June", "July","August", "September", "October",
"November", "December"];
d.setDate(d.getDate() - 1);
document.getElementById("demo").innerHTML = days[d.getDay()]+" "+month[d.getMonth()]+" "+(d.getDate()<10?"0"+d.getDate():d.getDate())+" "+d.getFullYear();
</script>
答案 3 :(得分:0)
找到以下代码,以dd/mm/yyyy
格式格式化日期。
function formatDate(d) {
if (!d) return null;
var date = d.getDate(), month = d.getMonth(), year = d.getFullYear();
return addZero(date)+"/"+addZero(month+1)+"/"+year;
}
function addZero(val) {
return val<10? "0"+val: val;
}
var d = new Date();
d.setDate(d.getDate() - 1);
formatDate(d);
答案 4 :(得分:0)
您基本上有以下功能:
getMonth()
getDay()
getFullYear()
getDate()
因此您可以使用它以您自己的方式格式化日期。这是一个例子:
var day = {"sunday","monday","tuesday","wednesday","thrusday","friday","saturday"};
var date = new Date();
date.setDate(date.getDate()-1);
var a=date.getDay();
var b=date.getMonth();
var c=date.getDate();
var d=date.getFullYear();
console.log(day[a]+" "+b+" "+c+" "+d);
如果您想以更合适的方式格式化日期和时间,建议您使用moment.js。
答案 5 :(得分:0)
你可以使用子串
<p id="demo"></p>
<script type='text/javascript'>
var d = new Date();
d.setDate(d.getDate() - 1);
d = d.toString().substring(0,15);
document.getElementById("demo").innerHTML = d;//Sun May 01 2016
</script>