两个日期之间的周和日 - Javascript

时间:2016-02-24 17:25:34

标签: javascript html

我想简单地显示直到明年圣诞节的几周和几天。我现在可以显示要显示的周数或显示的日期,但不能同时显示。

这是我的html文件。      
     
     JavaScript中的日期计算器

 <script src="datecalculator.js"> </script>

 <style>

  p 
  {
    color:red;        
  }

  .dateformat
  {
    background-color: yellow;
  }


  </style>

  </head>

 <body> 

 <script>
  function getDate()
  { 
    document.getElementById('demo').innerHTML = "Today's date is: " + new Date();  
  }

 </script>

 <button onclick="getDate()">Get Today's Date</button> <br/> <br />

 <button onclick="daystoChristmas()"> Get Days left until next   Christmas </button>

 <p id="demo"></p>

 <p id="demo1" class="dateformat"></p>

 </body> 
 </html>

这是我的外部JavaScript文件:

function daystoChristmas()
{ 

today = new Date();
window.alert("Today's date is: " + today);
xmas = new Date("December 25, 2016");    
msPerDay = 24 * 60 * 60 * 1000;
msLeft = (xmas.getTime() - today.getTime());
daysLeft = Math.round(msLeft/msPerDay);      
document.getElementById('demo1').innerHTML = daysLeft + " Days left    until next Christmas"; 

}

1 个答案:

答案 0 :(得分:0)

你去吧

function daystoChristmas()
{ 

today = new Date();
window.alert("Today's date is: " + today);
xmas = new Date("December 25, 2016");    
msPerDay = 24 * 60 * 60 * 1000;
msLeft = (xmas.getTime() - today.getTime());
daysLeft = Math.round(msLeft/msPerDay);
weeksLeft = Math.floor(daysLeft/7);
daysLeft = daysLeft % 7;
document.getElementById('demo1').innerHTML = weeksLeft + " weeks and "+daysLeft+" days left    until next Christmas"; 
}
<style>

  p 
  {
    color:red;        
  }

  .dateformat
  {
    background-color: yellow;
  }


  </style>

  </head>

 <body> 

 <script>
  function getDate()
  { 
    document.getElementById('demo').innerHTML = "Today's date is: " + new Date();  
  }

 </script>

 <button onclick="getDate()">Get Today's Date</button> <br/> <br />

 <button onclick="daystoChristmas()"> Get Days left until next   Christmas </button>

 <p id="demo"></p>

 <p id="demo1" class="dateformat"></p>

 </body>