JavaScrip日期、時間格式化
阿新 • • 發佈:2021-02-19
技術標籤:javascriptjs
自行封裝函式,格式化輸出當前系統時間
JS中提供了獲取日期指定部分的程式碼:
var myDate = new Date();//獲取當前系統時間
myDate.getFullYear(); //獲取年
myDate.getMonth();//獲取月(返回值0——11,0代表1月——11代表12月)
myDate.getDate(); //獲取日
myDate.getDay(); //獲取星期(返回值0——6,0代表星期天,1星期一——6星期六)
myDate.getTime(); //獲取當前時間(返回值從1970年1月1日0時0分0秒至當前時間的毫秒數)
myDate.getHours (); //獲取時(返回值0——23)
myDate.getMinutes(); //獲取分(0——59)
myDate.getSeconds(); //獲取秒(0——59)
myDate.getMilliseconds(); //獲取毫秒(0——999)
myDate.toLocaleDateString(); //獲取當前日期
將日期、時間格式化輸出為 20xx年xx月xx日 xx時xx分xx秒 星期x
eg:
程式碼
function addZero(num) { //0-9間的值格式化為01-09
if (num < 10)
return '0' + num;注意:數字型會轉為字串型!
else
return num;
}
function putDate() { //格式化輸出
var myDate = new Date();
var arr = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
return myDate.getFullYear() + '年' + addZero(myDate.getMonth() + 1) + '月' +
addZero(myDate.getDate ()) + '日' + ' ' + addZero(myDate.getHours()) + '時' +
addZero(myDate.getMinutes()) + '分' + addZero(myDate.getSeconds()) + '秒' +
' ' + arr[myDate.getDay()];
}
console.log(putDate());
想改為其他格式,只需修改函式putDate中的字元,修改為20xx-xx-xx xx:xx:xx 星期x
程式碼
function addZero(num) { //0-9間的值格式化為01-09
if (num < 10)
return '0' + num;注意:數字型會轉為字串型!
else
return num;
}
function putDate() { //格式化輸出
var myDate = new Date();
var arr = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
return myDate.getFullYear() + '—' + addZero(myDate.getMonth() + 1) + '—' +
addZero(myDate.getDate()) + ' ' + addZero(myDate.getHours()) + ':' +
addZero(myDate.getMinutes()) + ':' + addZero(myDate.getSeconds()) + ' ' +
arr[myDate.getDay()];
}
console.log(putDate());