显示昨天的日期

时间:2015-02-21 20:37:11

标签: javascript

如何修改以下代码以显示昨天的日期而不是今天的日期?例如," 2015年2月1日星期日和#34;应该成为" 2015年1月31日星期六"。

<script type="text/javascript">
<!--
  // Array of day names
  var dayNames = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
  // Array of month Names
  var monthNames = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
  var now = new Date();
  document.write(dayNames[now.getDay()] + ", " + 
  monthNames[now.getMonth()] + " " + 
  now.getDate() + ", " + now.getFullYear());
// -->
</script>

1 个答案:

答案 0 :(得分:1)

只需添加一行now.setDate(now.getDate()-1);即可将日期设置为昨天的日期。

  var dayNames = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
  var monthNames = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
  var now = new Date();
  now.setDate(now.getDate()-1);
  document.write(dayNames[now.getDay()] + ", " + 
  monthNames[now.getMonth()] + " " + 
  now.getDate() + ", " + now.getFullYear());