前言
延續 new Date( ) 語法,怎麼印出想要的資料格式?
任務
假設今天時間為 8/13,則需透過 new Date( ) 處理後,印出以下資料:
任務一、目前時間是 2020/8/13 9:23
任務二、2020/08/13
任務三、2020-08-13
任務四、今天是星期四
任務五、今天是九月十四日,時間為 13:10
HTML
<h1 id="heading"></h1>
<h3 id="first"></h3>
<h3 id="second"></h3>
<h3 id="third"></h3>
<h3 id="fourth"></h3>
<h3 id="fifth"></h3>
JavaScript
- 先宣告
DOM元素 - 使用
new Date( )相關語法,定義:日期、時間、年、月、日、時、分、秒
const heading = document.querySelector('#heading');
const first = document.querySelector('#first');
const second = document.querySelector('#second');
const third = document.querySelector('#third');
const fourth = document.querySelector('#fourth');
const fifth = document.querySelector('#fifth');
const today = new Date();
const todayTimestamp = Date.now();
const year = today.getFullYear();
const month = today.getMonth() + 1;
const date = today.getDate();
const hour = today.getHours();
const minute = today.getMinutes();
const day = today.getDay();
dataValues = [
today.getFullYear(),
today.getMonth()+1,
today.getDate(),
today.getHours(),
today.getMinutes(),
today.getSeconds(),
];
任務一、印出:目前時間是 2020/8/13 9:23
let date1 = `目前時間是 ${year}/${month}/${date} ${hour}:${minute}`;
// 目前時間是 2020/8/13 9:23
first.textContent = date1;
任務二、印出:2020/08/13
要依照自己定義的時間格式呈現,我們可以使用日期格式化的方法 DateFormat.js 擴充套件,
將 Date 轉化為指定格式的 String。
使用規範
月(M)、日(d)、小時(h)、分(m)、秒(s)、季度(q) 可以用 1-2 個佔位符,
年(y)可以用 1-4 個佔位符,毫秒(S)只能用 1 個佔位符(是 1-3 位的數字)。
例子:
(new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
(new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
格式化时间函数
可以看到下 obj 物件的 key 代表 regular expression 的規則,而 key 裡面的 + 號,指的是匹配前一字元 1 至多次,等同
於 {1,}。例如: /a+/ 匹配 「candy」 中的 a,以及所有 「caaaaaaandy」 中的 a 。
再來看到 for (let key in obj) { } 裡面的 const regex = new RegExp((${key})) ,這邊的 ${key} 需要用括號 ( ) 包住
,可參考 capturing parentheses ,括號會記住此次的匹配,之後用 RegExp.$1..$n 呼叫。
而 format.replace( ) 裡面的 RegExp.$1 會回傳 M 跟 d 的長度,如果是 MM 就會組合成 00+月 = 008 再去刪掉最前方的 0
也就是 obj[key].length。
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(), // 秒
"q+": Math.floor((this.getMonth() + 3) / 3), // 季度
"S": this.getMilliseconds() // 毫秒
};
for (let key in obj) {
// create a regular expression
const regex = new RegExp(`(${key})`);
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))
);
} else {
format = format.replace(regex, obj[key]);
}
}
}
console.log(format);
return format;
};
使用方法
var now = new Date();
var year = now.dateFormat("yyyy"); // 2020
var month = now.dateFormat("MM"); // 08
var day = now.dateFormat("dd"); // 13
var date = now.dateFormat("yyyy-MM-dd"); // 2020-08-13
var date_1 = now.dateFormat("yyyy/MM/dd"); // 2020/08/13
var date_2 = now.dateFormat("yyyyMMdd"); // 20200813
var date_time = now.dateFormat("yyyy-MM-dd hh:mm:ss"); // 2020-08-13 11:15:16
var date_time_1 = now.dateFormat("yyyy年MM月dd日 hh时mm分ss秒"); // 2020年08月13日 11时15分16秒
var date_time_2 = now.dateFormat("yyyy-MM-dd hh:mm:ss.S"); // 2020-08-13 11:15:16.597
var simple_time = now.dateFormat("yyyy-M-d h:m:s.S"); // 2020-8-13 11:15:16.597
介紹完日期格式化的方法後,來看一下實際範例:
Date.prototype.format = function(fmt){
var o = {
"M+" : this.getMonth()+1, //月份
"d+" : this.getDate(), //日
"h+" : this.getHours(), //小時
"m+" : this.getMinutes(), //分
"s+" : this.getSeconds(), //秒
"q+" : Math.floor((this.getMonth()+3)/3), //季
"S" : this.getMilliseconds() //毫秒
};
// RegExp.prototype.text()
// https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
// regex: +
// 匹配前一字元 1 至多次,等同於 {1,}。
// 例如:/a+/ 匹配「candy」中的 a,以及所有「caaaaaaandy」中的 a。
if(/(y+)/.test(fmt)){
fmt = fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
}
for(var k in o){
if(new RegExp("("+ k +")").test(fmt)){
// console.log('o[k]: ', o[k]);
// console.log('00 + o[k]: ', ("00" + o[k]).substr(1));
fmt = fmt.replace(
RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
}
}
return fmt;
}
let date2 = today.format('yyyy/MM/dd'); //2020/08/13
second.textContent = date2;
任務三、印出:2020-08-13
使用 toISOString() 語法 輸出格式的字符串: YYYY-MM-DDTHH:mm:ss.sssZ 時區是UTC(協調世界時)。
使用 split( ) 語法 指定的分隔符字符串將一個String對象分割成子字符串數組,以一個指定的分割字串
來決定每個拆分的位置。
let date3 = today.toISOString(); // 2020-08-13T01:23:34.280Z
third.textContent = date3.split('T')[0]; // 2020-08-13 (UTC time)
任務四、印出:今天是星期四
const weekday = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
let date4 = `今天是 ${weekday[today.getDay()]}`; // 今天是星期四
fourth.textContent = date4;
任務五、印出:今天是九月十四日,時間為 13:10
const numberToChinese = ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '二十', '二十一', '二十二', '二十三', '二十四', '二十五', '二十六', '二十七', '二十八', '二十九', '三十', '三十一'];
let date5 = `今天是${numberToChinese[month]}月${numberToChinese[date]}日,時間為 ${hour}:${minute}`;
// 今天是九月十四日,時間為 13:10
fifth.textContent = date5;