一.比較時間的大小(由頁面插件選擇的日期時間)
var startDateStr = '2017-03-11 10:00:00';
var endDateStr = '2017-03-11 9:59:59';
var startDate = dateFormat(startDateStr);
var endDate = dateFormat(endDateStr);
if ((startDate-endDate) >= 0) {
alert('結束時間必須大於開始時間');
}
function dateFormat(dateStr) {
if (dateStr.indexOf(':') > -1){ //日期+時間
var tempArr = dateStr.split(' ');
var dArr = tempArr[0].replace(/[-\/]/g, ',').split(',');
var tArr = tempArr[1].replace(/(:)/g, ',').split(',');
return new Date(parseInt(dArr[0]), parseInt(dArr[1]), parseInt(dArr[2]), parseInt(tArr[0]), parseInt(tArr[1]), parseInt(tArr[2]));
} else { //日期
var dArr = dateStr.replace(/[-\/]/g, ',').split(',');
return new Date(parseInt(dArr[0]), parseInt(dArr[1]), parseInt(dArr[2]));
}
}
二.將後臺取出的時間戳轉化成指定格式的日期
function getDate(date, format) {
// format: yyyy-MM-dd hh:mm:ss
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (date.getFullYear() + '').substring(4 - RegExp.$1.length));
}
var o = {
'(M+)': date.getMonth(),
'(d+)': date.getDate(),
'(h+)': date.getHours(),
'(m+)': date.getMinutes(),
'(s+)': date.getSeconds()
};
for (var key in o) {
var reg = new RegExp(key);
if (reg.test(format)) {
format = format.replace(RegExp.$1, addLeftZero(o[key] + ''));
}
}
return format;
};
function addLeftZero(str) {
return str.length > 1 ? str : '0' + str;
}
三.求時間差(天、時、分、秒)
var startDateStr = '2017-03-11 10:00:00'; //假定獲取的input中時間值
var endDateStr = '2017-03-12 10:59:59';
remainTime(startDateStr,endDateStr);
function remainTime(startDateStr, endDateStr) {
var startDate = dateFormat(startDateStr);
var endDate = dateFormat(endDateStr);
var t = (endDate - startDate)/1000; //相差秒數 等價於=>(endDate.getTime() - startDate.getTime())/1000
var days = Math.floor(t/86400); //相差天數
var hours = Math.floor(t%86400/3600); //相差小時
var minutes = Math.floor(t%86400%3600/60); //相差分鐘
var seconds = Math.floor(t%60); //相差秒
console.log(days+'天'+hours+'小時'+minutes+'分鐘'+seconds+'秒'); //1天0小時59分鐘59秒
}
//轉化爲時間對象Object
function dateFormat(dateStr) {
if (dateStr.indexOf(':') > -1){ //日期+時間
var tempArr = dateStr.split(' ');
var dArr = tempArr[0].replace(/[-\/]/g, ',').split(',');
var tArr = tempArr[1].replace(/(:)/g, ',').split(',');
return new Date(parseInt(dArr[0]), parseInt(dArr[1]), parseInt(dArr[2]), parseInt(tArr[0]), parseInt(tArr[1]), parseInt(tArr[2]));
} else { //日期
var dArr = dateStr.replace(/[-\/]/g, ',').split(',');
return new Date(parseInt(dArr[0]), parseInt(dArr[1]), parseInt(dArr[2]));
}
}