How to display yesterdays date in day, dd/mm/yyyy format in JavaScript
本问题已经有最佳答案,请猛点这里访问。
我想使用JavaScript显示昨天的日期。 为此,我使用如下代码:
1 2 3 4 5 6 7 | <p id="demo"> </p> <script type=text/javascript> var d = new Date(); d.setDate(d.getDate() - 1); document.getElementById("demo").innerHTML = d; |
它有效,但会以完整的格式显示日期:
Sun May 01 2016 11:31:53 GMT-0700 (Pacific Daylight Time)
我想只显示这样的日期和日期格式:
Sun May 01 2016
这有什么解决方案吗?
如果您可以灵活使用外部库,则可以使用moment.js。
1 | document.write(moment().add(-1,"days").format("ddd MMM DD YYYY")) |
1 | <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"> |
1 2 3 4 5 6 7 8 9 10 | <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(); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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; |
你可以使用子串
1 2 3 4 5 6 7 | <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 |
你基本上有以下功能:
1 2 3 4 | getMonth() getDay() getFullYear() getDate() |
因此您可以使用它以您自己的方式格式化日期。 这是一个例子:
1 2 3 4 5 6 7 8 9 10 | 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。
找到以下代码,以
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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); |