一 、获取前几天的日期,日期相减,date是当前日期,days是天数
//日期相减
function reduceDate(date,days) {
var d = new Date(date);
d.setDate(d.getDate() - days);
var m = d.getMonth() + 1;
if (m < 10) {
m = "0" + m;
}
var day = d.getDate();
if (d.getDate() < 10) {
day = "0" + day;
}
return d.getFullYear() + '-' + m + '-' + day;
}
二 、获取前一个月的日期,date是当前日期
// 获取前一个月的日期
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) {//如果是1月份,则取上一年的12月份
year2 = parseInt(year2) - 1;
month2 = 12;
}
var day2 = day;
var days2 = new Date(year2, month2, 0);
days2 = days2.getDate();
if (day2 > days2) {//如果原来日期大于上一月的日期,则取当月的最大日期。比如3月的30日,在2月中没有30
day2 = days2;
}
if (month2 < 10) {
month2 = '0' + month2;//月份填补成2位。
}
var t2 = year2 + '-' + month2 + '-' + day2;
return t2;
}
三、日期相减
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date d1 = df.parse("2020-03-26 11:11:00");
Date d2 = df.parse("2020-03-27 11:11:01");
long diff = d2.getTime() - d1.getTime();
long days = diff / (1000 * 60 * 60 * 24);
diff = diff - days * (1000 * 60 * 60 * 24);
long hours = diff / (1000 * 60 * 60);
diff = diff - hours * (1000 * 60 * 60);
long minutes = diff / (1000 * 60);
diff = diff - minutes * (1000 * 60);
long seconds = diff / 1000;
System.out.println(""+days+"天"+hours+"小时"+minutes+"分"+seconds+"秒");
} catch (Exception e) {
}