计算日期方法

/**
* 计算两个日期相差的天数
* @param s 开始时间
* @param e 结束时间
* @return
* @throws Exception
*/

public int daysBetween(String s,String e) throws Exception{    
       Calendar cal = Calendar.getInstance();    
       cal.setTime(Date.valueOf(s));    
       long time1 = cal.getTimeInMillis();                 
       cal.setTime(Date.valueOf(e));    
       long time2 = cal.getTimeInMillis();         
       long between_days=(time2-time1)/(1000*3600*24);  
           
      return Integer.parseInt(String.valueOf(between_days));           

}   

/**
* 计算两个日期相差的月数
* @param s 开始时间
* @param e 结束时间
* @return
*/

public int getMonthDiffer(String s,String e) throws Exception{
//GregorianCalendar 是 Calendar 的一个具体子类,提供了世界上大多数国家/地区使用的标准日历系统。
//GregorianCalendar 是一种混合日历
Calendar cal1 = new GregorianCalendar();
cal1.setTime(Date.valueOf(s));
Calendar cal2 = new GregorianCalendar();
cal2.setTime(Date.valueOf(e));
//获取相差月数
int c = (cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR)) * 12 + 
cal1.get(Calendar.MONTH) - cal2.get(Calendar.MONTH);
//如果结果=0就返回1,否则就取结果的绝对值
return c == 0 ? 1 : Math.abs(c);
}




/**
* 时间戳加上秒数
* @param date  日期时间戳
* @param second 秒数
* @return 返回一个时间戳
*/

public String addDate(String date, long second) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date dt1 = df.parse(date);
long seconds = dt1.getTime() + second * 1000L;
Date d = new Date(seconds);
return df.format(d);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}


/**
* 两个时间比较大小
* @param DATE1 时间1
* @param DATE2 时间2
* @return
*/

public boolean compare_date(String DATE1, String DATE2) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date dt1 = df.parse(DATE1);
Date dt2 = df.parse(DATE2);
if (dt1.getTime() > dt2.getTime()) {
return true;
} else {
return false;
}
} catch (Exception exception) {
exception.printStackTrace();
}
return false;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值