JavaScript Date getTime() 方法



在 JavaScript 中,Date.getTime() 方法將返回一個數值,該數值表示日期物件和紀元之間以毫秒為單位的差值。紀元是時間以秒為單位測量的起點,定義為 1970 年 1 月 1 日 00:00:00 UTC。

當提供的 Date 物件無效時,此方法將返回非數字 (NaN)。返回值始終為非負整數。

此方法在功能上等效於 valueOf() 方法。

語法

以下是 JavaScript Date getTime() 方法的語法:

getTime();

此方法不接受任何引數。

返回值

此方法返回一個數值,表示指定的日期和時間與 Unix 紀元之間的毫秒數。

示例 1

在下面的示例中,我們演示了 JavaScript Date getTime() 方法的用法:

<html>
<body>
<script>
   const currentDate = new Date();
   const timestamp = currentDate.getTime();

   document.write(timestamp);
</script>
</body>
</html>

輸出

上述程式返回自紀元以來的毫秒數。

示例 2

在下面的示例中,我們將特定日期和時間 (2023-12-26 06:30:00) 提供給日期物件:

<html>
<body>
<script>
   const currentDate = new Date('2023-12-26 06:30:00');
   const timestamp = currentDate.getTime();

   document.write(timestamp);
</script>
</body>
</html>

輸出

它返回“1703574000000”毫秒作為輸出。

示例 3

在下面的示例中,日期物件是用無效日期建立的,即超出有效範圍的日期和時間值。

<html>
<body>
<script>
   const specificDate = new Date('2023-15-56 06:30:00');
   const dateString = specificDate.getTime();

   document.write(dateString);
</script>
</body>
</html>

輸出

程式返回“NaN”作為結果。

廣告