DIV CSS 佈局教程網

用 JavaScript 取得當前日期並格式化為 YYYY-MM-DD
編輯:關於JavaScript     

在日常開發中,經常需要把當前日期整理成 YYYY-MM-DD 這種標準格式,無論是顯示還是傳給後端都相當實用。下面的程式碼示範了如何用 JavaScript 達成這個需求:

 var nowDate = new Date(); var year = nowDate.getFullYear(); var month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1; var day = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate(); var dateStr = year + "-" + month + "-" + day; 

這段程式碼的關鍵在於「補零」處理:由於 getMonth() 回傳的是 0 到 11 的索引值,所以要記得加 1;而月和日若小於 10,就在前面補上一個 0,確保輸出固定為兩位數。如此一來,就能穩定得到如 2026-09-21 這樣整齊的日期字串了。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved