JavaScript 中的 Date.now() 函式


日期物件是 JavaScript 語言中內建的一種資料型別。使用 new Date( ) 如下所示建立日期物件。

一經建立 Date 物件,您可以使用許多方法進行操作。大多數方法只需讓您獲取並設定物件的年、月、日、小時、分鐘、秒和毫秒欄位,使用本地時間或 UTC(通用,或 GMT)時間。

Date 物件的 now() 函式返回自 1st Jan 1970 年起的毫秒數。

語法

其語法如下

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)

上次更新:25-6 月 -2020

216 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始入門
廣告
© . All rights reserved.