js中两个日期大小比较,获取当前日期,日期加减一天
一.两个日期大小比较
1.格式:(yyyy-mm-dd)
function duibi(a, b,flag) {
var arr = a.split("-");
var starttime = new Date(arr[0], arr[1], arr[2]);
var starttimes = starttime.getTime();
var arrs = b.split("-");
var endTime = new Date(arrs[0], arrs[1], arrs[2]);
var endTimes = endTime.getTime();
if (endTimes >= starttimes) {
flag = "true";
return flag;
}else{
flag = "false";
return flag;
}
}
2.格式:(yyyy-mm-dd hh:mi:ss)
function comptime() {
var beginTime = "2009-09-21 00:00:00";
var endTime = "2009-09-21 00:00:01";
var beginTimes = beginTime.substring(0, 10).split('-');
var endTimes = endTime.substring(0, 10).split('-');
beginTime = beginTimes[1] + '-' + beginTimes[2] + '-' + beginTimes[0] + ' ' +beginTime.substring(10, 19);
endTime = endTimes[1] + '-' + endTimes[2] + '-' + endTimes[0] + ' ' + endTime.substring(10, 19);
alert(beginTime + "aaa" + endTime);
alert(Date.parse(endTime));
alert(Date.parse(beginTime));
var a = (Date.parse(endTime) - Date.parse(beginTime)) / 3600 / 1000;
if (a < 0) {
alert("endTime小!");
} else if (a > 0) {
alert("endTime大!");
} else if (a == 0) {
alert("时间相等!");
} else {
return 'exception'
}
}
二.JS中获取日期前一个月的日期
#参数date格式 : yyyy-mm-dd
function getPreMonth(date) {
var arr = date.split('-');
var year = arr[0]; //获取当前日期的年份
var month = arr[1]; //获取当前日期的月份
var day = arr[2]; //获取当前日期的日
var days = new Date(year, month, 0);
days = days.getDate(); //获取当前日期中月的天数
var year2 = year;
var month2 = parseInt(month) - 1;
if (month2 == 0) {
year2 = parseInt(year2) - 1;
month2 = 12;
}
var day2 = day;
var days2 = new Date(year2, month2, 0);
days2 = days2.getDate();
if (day2 > days2) {
day2 = days2;
}
if (month2 < 10) {
month2 = '0' + month2;
}
var t2 = year2 + '-' + month2 + '-' + day2;
return t2;
}