JS Day 42: Date() 方法&日期格式
Getter
取得時間格式
const today = new Date(); // Date Sat Aug 08 2020 00:28:32 GMT+0800 (Taipei Standard Time)
// 回傳年份
today.getFullYear(); // 2020
// 回傳月份 (0-11) ** 從 0 開始
today.getMonth(); // 7
// 回傳日期(1-31)
today.getDate(); // 8
// 回傳小時(0-23)
today.getHours(); // 0
// 回傳分鐘(0-59)
today.getMinutes(); // 28
// 回傳日期(0-6)** 從 0 開始
today.getDay(); // 6
Setter
設定時間格式
// 設定月份中的日期
today.setDate();
const bday = new Date('August 08, 2020 11:26:15');
event.setDate(05); // 設定程 5 號
// => 1596597975000
console.log(event); // Date Wed Aug 05 2020 11:26:15 GMT+0800 (Taipei Standard Time)
// 設定完整年份
today.setFullYear();
// 設定月份
today.setMonth();
// 設定小時
today.setHours();
// 設定分鐘
today.setMinutes();
// 設定秒數
today.setSeconds();
時間格式
設定時間格式 例:2020/08/05
const setDate = new Date(2020, 07, 05);
let df = (date) => {
const year = date.getFullYear();
const month = date.getMonth()+1;
const day = date.getDate();
return [year, month, day].join("/");
};
console.log(df(setDate));
不過這樣寫不夠靈活。如果遇到格式是 2020-8-5 或是 2020-08-05 整式函式都要重寫。
Date.prototype.dateFormat = function(format){
var obj = {
// 這邊的 this 會指向 Date()
"y+": this.getFullYear(), //年
"M+": this.getMonth()+1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小時
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"S" : this.getMilliseconds() //毫秒
};
// 物件的 key 代表 regular expression 的規則
// +號:匹配前一字元 1 至多次,等同於 {1,}。
// 例如:/a+/ 匹配「candy」中的 a,以及所有「caaaaaaandy」中的 a。
for (let key in obj) {
// create a regular expression
const regex = new RegExp(`(${key})`); // 這邊的 key 需要用括號包住( ),參考 capturing parentheses
// 括號會記住此次的匹配,之後用以用 RegExp.$1..$n 呼叫
if (regex.test(format)) {
if (regex == '/(M+)/' || regex == '/(d+)/') {
format = format.replace(
regex, (RegExp.$1.length < 2 ? obj[key] : ("00" + obj[key]).substring(1,obj[key].length))
// RegExp.$1 會回傳 M 跟 d 的長度
// 如果是 MM 就會組合成 00+月 = 008 再去刪掉最前方的0 也就是 obj[key].length
);
} else {
format = format.replace(regex, obj[key]);
}
}
}
console.log(format);
return format;
}
let ccc = new Date().dateFormat('yyyy/MM/d'); // 2020/08/8
let aaa = new Date().dateFormat('yyyy-M-dd'); // 2020-8-08
let bbb = new Date().dateFormat('yyyy/MM/dd'); // 2020/08/08
Reference:
JavaScript Date (日期) 對象
RegExp.prototype.test() – MDN web docs
Regular Expression: + (plus sign) — MDN web docs
Regular Expression: Capturing Parentheses — MDN web docs
本作品采用 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议 进行许可。