当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Javascript getTime()用法及代码示例


getTime()方法是Javascript中的Date对象的方法。此方法返回自1970年1月1日以来的毫秒数。创建新的Date对象时,它将存储创建时的日期和时间数据。在此日期对象上调用getTime()方法时,它将返回自1970年1月1日(Unix纪元)以来的毫秒数。

用法:

Date.getTime()

返回类型:一个等于Unix Epoch的秒数的数值。


示例1:

<!DOCTYPE html> 
<html lang="en"> 
  
<head> 
    <meta charset="UTF-8"> 
    <meta name="viewport" 
          content="width=device-width,  
                   initial-scale=1.0"> 
    
    <meta http-equiv="X-UA-Compatible" 
          content="ie=edge"> 
    
    <title>Document</title> 
</head> 
  
<body> 
    <div> 
        <h4>Today's Date:
          <span class="date"> 
          </span> 
      </h4> 
    </div> 
    <div> 
        <h4>getTime():  
          <span class="time"> 
          </span> 
      </h4> 
    </div> 
</body> 
<script> 
    var Today = new Date(); 
    var date =  
        document.querySelector(".date"); 
    
    var time =  
        document.querySelector(".time"); 
  
    time.innerHTML = Today.getTime(); 
    date.innerHTML = Today; 
</script> 
  
</html>

输出:

示例2:

<!DOCTYPE html> 
<html lang="en"> 
  
<head> 
    <meta charset="UTF-8"> 
    <meta name="viewport"
          content="width=device-width,  
                   initial-scale=1.0"> 
    <meta http-equiv="X-UA-Compatible" 
          content="ie=edge"> 
    <title>Document</title> 
</head> 
  
<body> 
    <div> 
        <h4>Birth Date:
          <span class="date"> 
          </span> 
      </h4> 
    </div> 
    <div> 
        <h4>getTime():
          <span class="time"> 
          </span> 
      </h4> 
    </div> 
    <div> 
        <h4>I am  
          <span class="years"> 
          </span> years old. 
      </span> 
  </h4> 
    </div> 
</body> 
<script> 
    var BD = new Date("July 29, 1997 23:15:20"); 
    var date = document.querySelector(".date"); 
    var time = document.querySelector(".time"); 
    var Today = new Date(); 
    var today = Today.getTime(); 
    var bd = BD.getTime(); 
    var year = 1000 * 60 * 60 * 24 * 365; 
    var years = (today - bd) / year; 
    date.innerHTML = BD; 
    time.innerHTML = BD.getTime(); 
    var y = document.querySelector(".years"); 
    y.innerHTML = Math.round(years); 
</script> 
  
</html>

输出:



相关用法


注:本文由纯净天空筛选整理自Pankaj_Singh大神的英文原创作品 JavaScript | getTime() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。