获取date类型
var type = _xAxis[0].split(/-|:|\s/).length;
按时间粒度获取date的时间差
function getDateDiffByType(newDate,endDate,type){ newDate = new Date(newDate) == ‘Invalid Date‘ ? newDate+‘:00‘ : newDate; endDate = new Date(endDate) == ‘Invalid Date‘ ? endDate+‘:00‘ : endDate; var dateDiff = new Date(endDate)-new Date(newDate); var _date = new Date(dateDiff); var year = _date.getFullYear() - 1970; var month = _date.getMonth(); switch (type) { case 1: { return year; break; } case 2: { return month+year*12; break; } case 3: { return dateDiff/1000/60/60/24; break; } case 4: { return dateDiff/1000/60/60; break; } case 5: { return dateDiff/1000/60; break; } case 6: { return dateDiff/1000; break; } } }
附:date按时间粒度格式化
function dateFmtByType( _date,_type) { _date = new Date(_date) == ‘Invalid Date‘ ? _date+‘:00‘ : _date;//"2017-02-12 12"是Invalid Date var date = new Date(_date); var fmt = ["yyyy","yyyy-MM","yyyy-MM-dd","yyyy-MM-dd hh","yyyy-MM-dd hh:mm","yyyy-MM-dd hh:mm:ss"]; return date.dateFormat(fmt[_type-1]); }
附:date格式化代码("yyyy-MM-dd hh:mm:ss")
Date.prototype.dateFormat = function(fmt) { //author: meizz 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() //毫秒 }; 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)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length))); return fmt; }