一.比较时间的大小(由页面插件选择的日期时间)
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) {
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';
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;
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+'秒');
}
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]));
}
}