當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


JavaScript Date.now()用法及代碼示例

Date 對象是 JavaScript 語言中內置的一種數據類型。日期對象是使用 new Date( ) 創建的,如下所示。

創建 Date 對象後,可以使用多種方法對其進行操作。大多數方法隻允許您使用本地時間或 UTC(通用或 GMT)時間獲取和設置對象的年、月、日、小時、分鍾、秒和毫秒字段。

Date對象的now()函數返回從1開始的毫秒數st1970 年 1 月。

用法

其語法如下

Date.now();

示例

<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var currentDate = Date.now();
      var birthDate = Date.parse('29 sep 1989 00:4:00 GMT');
      document.write(currentDate);
      document.write(", "+birthDate+", ");
      document.write(currentDate - birthDate);
   </script>
</body>
</html>

輸出

1537780591654, 623030640000, 914749951654

示例

您可以使用此函數獲取當前日期,但由於它返回 1970 年 1 月 1 日起的毫秒數以獲取格式化日期,因此將獲得的值傳遞給 Date 構造函數。

<html>
<head>
   <title>JavaScript Example</title>
</head>
<body>
   <script type="text/javascript">
      var currentDate = Date.now();
      document.write(currentDate);
      document.write("<br>");
      document.write(Date(currentDate).toString());
   </script>
</body>
</html>

輸出

1539758885099
Wed Oct 17 2018 12:18:05 GMT+0530 (India Standard Time)

相關用法


注:本文由純淨天空篩選整理自Karthikeya Boyini大神的英文原創作品 Date.now() function in JavaScript。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。