網站首頁 學習教育 IT科技 金融知識 旅遊規劃 生活小知識 家鄉美食 養生小知識 健身運動 美容百科 遊戲知識 綜合知識
當前位置:趣知科普吧 > IT科技 > 

獲取當前日期|js

欄目: IT科技 / 發佈於: / 人氣:2.13W

在JavaScript中若是想要獲取當前日期能夠使用Date對象中的Date()方法來獲取當前時間。Date對象一般來說就是用於處理日期與時間的,而Date()方法可以返回當天的日期和時間。

說明:需要注意的是,Date對象會自動將當前日期與時間儲存爲其初始值。

語法格式爲:

Date()

js 獲取當前日期

參考範例:

示例一:

輸出今天的日期和時間,具體代碼爲:

<script type="text/javascript">

   document.write(Date())

</script>

輸出結果:

Wed Aug 14 2019 17:42:56 GMT+0800 (中國標準時間)

js 獲取當前日期 第2張

示例二:

若是想要格式化時間,已固定格式顯示時間,具體代碼爲:

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

</head>

<body>

<div id="timer"></div>

<script type="text/javascript">

function current() {

var d = new Date(),

str = '';

str += d.getFullYear() + '年'; //獲取當前年份 

str += d.getMonth() + 1 + '月'; //獲取當前月份(0——11) 

str += d.getDate() + '日';

str += d.getHours() + '時';

str += d.getMinutes() + '分';

str += d.getSeconds() + '秒';

return str;

}

window.onload = function() {

var timer = document.getElementById("timer");

timer.innerHTML = current();

}

</script>

</body>

</html>

輸出結果:

2019年8月14日17時57分17秒

Tags:js 獲取 日期