iT邦幫忙

2026 iThome 鐵人賽

DAY 16
0

網頁有時需要顯示現在的日期或時間,例如文章發布日期、活動日期或畫面上的時鐘。JavaScript可以使用Date處理這些資料。

首先使用new Date()建立一個日期物件。如果沒有放入任何資料,就會取得執行當下的日期與時間:

const now = new Date();
console.log(now);

https://ithelp.ithome.com.tw/upload/images/20260930/20178696R973CG2Dd9.png

直接輸出now會同時看到日期、時間和時區。如果只需要其中一部分,可以使用不同的方法分別取得:

const year = now.getFullYear();
const month = now.getMonth() + 1;
const date = now.getDate();

console.log(year);
console.log(month);
console.log(date);

https://ithelp.ithome.com.tw/upload/images/20260930/201786960fURPJUehn.png

getFullYear()取得年份,getMonth()取得月份,getDate()取得今天是幾號。要注意getMonth()是從 0 開始計算,0 代表一月、1 代表二月,所以顯示一般月份時要加 1。

時、分、秒也能分開取得:

const hours = now.getHours();
const minutes = now.getMinutes();
const seconds = now.getSeconds();

console.log(hours);
console.log(minutes);
console.log(seconds);

將這些結果放進樣板字串,就能組合成比較容易閱讀的文字:
https://ithelp.ithome.com.tw/upload/images/20260930/20178696M4g2quwCqk.png

const message = `現在是 ${year} 年 ${month} 月 ${date} 日,${hours} 點 ${minutes} 分`;
console.log(message);

https://ithelp.ithome.com.tw/upload/images/20260930/20178696BMxXc0AgQT.png

如果要知道星期幾,可以使用getDay()。它會回傳 0 到 6,0 代表星期日、1 代表星期一,以此類推。可以準備一個陣列,使用回傳的數字取得對應文字:

const weekdays = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
console.log(weekdays[now.getDay()]);

除了取得現在時間,也能建立指定日期。下面建立的是 2026 年 9 月 15 日上午 10 點 30 分:
這裡的月份同樣從 0 開始,因此九月得部分要填入 8。
https://ithelp.ithome.com.tw/upload/images/20260930/20178696GbYQmJzLg8.png

const eventDate = new Date(2026, 8, 15, 10, 30);
console.log(eventDate);

https://ithelp.ithome.com.tw/upload/images/20260930/20178696ZbJUzPVgUr.png


上一篇
Day15 解構
下一篇
Day17 DOM
系列文
從頭開始的Javascript學習之旅 共 17 篇
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言