在 HTML 中獲取今天的日期
-
使用 JavaScript
Date()
函式獲取 HTML 中的當前日期 -
在 HTML 中以
y/m/d
格式獲取當前日期 -
使用 HTML 中的 JavaScript 方法
toLocaleDateString()
獲取當前日期

在本文中,我們將介紹幾種獲取 HTML 中當前日期的方法。
使用 JavaScript Date()
函式獲取 HTML 中的當前日期
我們可以使用 JavaScript Date()
函式來獲取當前日期。該函式返回當前日期和時間。我們可以建立一個 HTML 容器並使用 JavaScript 在其中顯示當前日期。我們將使用 innerHTML
屬性在 HTML 中寫入日期。
例如,建立一個 div
並將 current_date
設定為它的 id
。然後,在 script
標籤中編寫一些 JavaScript。使用 getElementById
屬性選擇 current_id
並呼叫 Date()
函式。使用 innerHTML
屬性在 HTML 中寫入返回的日期。
下面的示例將顯示當前日期和時間,如下面的輸出部分所示。輸出包含星期幾、月、日、年、小時、分鐘、秒和 GMT 以及有關位置的資訊。
示例程式碼:
<div id="current_date">
<script>
document.getElementById("current_date").innerHTML = Date();
</script>
</div>
在 HTML 中以 y/m/d
格式獲取當前日期
我們還可以使用各種 JavaScript Date()
方法以 y/m/d
格式查詢當前日期。我們可以從 getFullYear()
方法獲取當前年份,從 getMonth()
方法獲取當前月份,從 getDate()
方法獲取當前日期。在這個方法中,我們將使用 Date()
物件來訪問這些不同的函式。我們可以以任何我們想要的方式格式化日期,並使用 innerHTML
屬性將其顯示在 HTML 頁面上。
例如,建立一個與上述方法具有相同 id 的 div
。在 JavaScript 中,建立 Date()
類的 date
物件。接下來,建立三個變數 year
、month
和 day
。使用 date
物件呼叫方法 getFullYear()
、getMonth()
和 getDate()
,並儲存在這些相應的變數中。接下來,使用 document
物件並呼叫 getElementById
屬性來選擇 div
的 id。接下來,將 innerHTML
設定為變數 month
、day
和 year
,以斜線分隔。
通過這種方式,我們可以使用 JavaScript Date()
類在 HTML 中以 m/d/y
格式獲取當前日期。
示例程式碼:
<div id="current_date">
<script>
date = new Date();
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
document.getElementById("current_date").innerHTML = month + "/" + day + "/" + year;
</script>
</div>
使用 HTML 中的 JavaScript 方法 toLocaleDateString()
獲取當前日期
我們可以使用 JavaScript 函式 toLocaleDateString()
來查詢當前日期。toLocaleDateString()
函式根據函式中提供的語言返回當前日期。有各種特定於語言的約定,我們可以使用 toLocaleDateString()
函式定義語言。該函式有兩個引數,分別是 locales
和 options
。我們可以通過 locales
選項指定輸出的語言。例如,我們可以對美國英語使用 en-US
,對英國英語使用 en-GB
。
例如,建立一個 div
並在 script
標籤內編寫 JavaScript。建立 Date()
類的 date
物件並呼叫方法 toLocaleDateString()
。接下來,使用 document.write()
顯示 date
變數。
我們可以看到 m/d/y
格式的輸出。因此,我們可以使用 toLocaleDateString()
方法在 HTML 中查詢當前日期。
示例程式碼:
<div>
<script>
date = new Date().toLocaleDateString();
document.write(date);
</script>
</div>
Subodh is a proactive software engineer, specialized in fintech industry and a writer who loves to express his software development learnings and set of skills through blogs and articles.
LinkedIn