当前位置: 移动技术网 > IT编程>开发语言>Java > JAVA计算两个日期相差的实例

JAVA计算两个日期相差的实例

2019年07月22日  | 移动技术网IT编程  | 我要评论

在java开发物流或是其他功能的时候会用到两个日期 相差多天的数据,所以整理了一下备用。
调用方式:

复制代码 代码如下:

long date1 = getdatetime("20121201");//可改成自己的日期类型,但以 “20121212”这种格式
long date2 = getdatetime("20121212");  
int day = dateinterval(date1, date2);  
system.out.println(day);
 

具体实现方法调用:
复制代码 代码如下:

/** 
 * 计算出两个日期之间相差的天数 
 * 建议date1 大于 date2 这样计算的值为正数 
 * @param date1 日期1 
 * @param date2 日期2 
 * @return date1 - date2 
 */ 
public static int dateinterval(long date1, long date2) {
    if(date2 > date1){
        date2 = date2 + date1;
        date1 = date2 - date1;
        date2 = date2 - date1;
    }

     // canlendar 该类是一个抽象类  
     // 提供了丰富的日历字段 
     // 本程序中使用到了 
     // calendar.year    日期中的年份 
     // calendar.day_of_year     当前年中的天数  
     // getactualmaximum(calendar.day_of_year) 返回今年是 365 天还是366 天 
    calendar calendar1 = calendar.getinstance(); // 获得一个日历  
    calendar1.settimeinmillis(date1); // 用给定的 long 值设置此 calendar 的当 前时间值。  

    calendar calendar2 = calendar.getinstance();
    calendar2.settimeinmillis(date2);
    // 先判断是否同年  
    int y1 = calendar1.get(calendar.year);
    int y2 = calendar2.get(calendar.year);

    int d1 = calendar1.get(calendar.day_of_year);
    int d2 = calendar2.get(calendar.day_of_year);
    int maxdays = 0;
    int day = 0;
    if(y1 - y2 > 0){
        day = numerical(maxdays, d1, d2, y1, y2, calendar2);
    }else{
        day = d1 - d2;
    }
    return day;
}  

/** 
 * 日期间隔计算 
 * 计算公式(示例): 
 *      20121201- 20121212
 *      取出20121201这一年过了多少天 d1 = 天数  取出 20121212这一年过了多少天 d2 = 天数
 *      如果2012年这一年有366天就要让间隔的天数+1,因为2月份有 29日。 
 * @param maxdays   用于记录一年中有365天还是366天 
 * @param d1    表示在这年中过了多少天 
 * @param d2    表示在这年中过了多少天 
 * @param y1    当前为2012年 
 * @param y2    当前为2012年 
 * @param calendar  根据日历对象来获取一年中有多少天 
 * @return  计算后日期间隔的天数 
 */ 
public static int numerical(int maxdays, int d1, int d2, int y1, int y2, calendar calendar){
    int day = d1 - d2;
    int betweenyears = y1 - y2;
    list<integer> d366 = new arraylist<integer>();

    if(calendar.getactualmaximum(calendar.day_of_year) == 366){
        system.out.println(calendar.getactualmaximum (calendar.day_of_year));
        day += 1;
    }

    for (int i = 0; i < betweenyears; i++) {
        // 当年 + 1 设置下一年中有多少天  
        calendar.set(calendar.year, (calendar.get (calendar.year)) + 1);
        maxdays = calendar.getactualmaximum (calendar.day_of_year);
        // 第一个 366 天不用 + 1 将所有366记录,先不进行 加入然后再少加一个  
        if(maxdays != 366){
            day += maxdays;
        }else{
            d366.add(maxdays);
        }
        // 如果最后一个 maxdays 等于366 day - 1  
        if(i == betweenyears-1 && betweenyears > 1 && maxdays == 366){
            day -= 1;
        }
    }

    for(int i = 0; i < d366.size(); i++){
        // 一个或一个以上的366天  
        if(d366.size() >= 1){
            day += d366.get(i);
        } 
    }  
    return day;
}

/** 
 * 将日期字符串装换成日期 
 * @param strdate   日期支持年月日 示例:yyyymmdd 
 * @return  1970年1月1日器日期的毫秒数 
 */ 
public static long getdatetime(string strdate) {
    return getdatebyformat(strdate, "yyyymmdd").gettime();
}

/** 
 * @param strdate   日期字符串 
 * @param format    日期格式 
 * @return      date 
 */ 
public static date getdatebyformat(string strdate, string format) {
    simpledateformat sdf = new simpledateformat(format);
    try{
        return (sdf.parse(strdate));
    }catch (exception e){
        return null;
    }
}
 

例2
复制代码 代码如下:

import java.text.parseexception;
import java.text.simpledateformat;
import java.util.calendar;
import java.util.date;

public class test16 {
 /**
  * @param args
  * @throws parseexception
  */
 public static void main(string[] args) throws parseexception {
  // todo auto-generated method stub
  simpledateformat sdf=new simpledateformat("yyyy-mm-dd hh:mm:ss");
  date d1=sdf.parse("2012-09-08 10:10:10");
  date d2=sdf.parse("2012-09-15 00:00:00");
  system.out.println(daysbetween(d1,d2));
  system.out.println(daysbetween("2012-09-08 10:10:10","2012-09 -15 00:00:00"));
 }

 /**
     * 计算两个日期之间相差的天数
     * @param smdate 较小的时间
     * @param bdate  较大的时间
     * @return 相差天数
  * @throws parseexception
     */ 
    public static int daysbetween(date smdate,date bdate) throws parseexception 
    { 
     simpledateformat sdf=new simpledateformat("yyyy-mm- dd");
     smdate=sdf.parse(sdf.format(smdate));
     bdate=sdf.parse(sdf.format(bdate));
        calendar cal = calendar.getinstance(); 
        cal.settime(smdate); 
        long time1 = cal.gettimeinmillis ();              
        cal.settime(bdate); 
        long time2 = cal.gettimeinmillis ();      
        long between_days=(time2-time1)/ (1000*3600*24);

       return integer.parseint(string.valueof (between_days));        
    } 

/**
*字符串的日期格式的计算
*/
    public static int daysbetween(string smdate,string bdate) throws parseexception{
     simpledateformat sdf=new simpledateformat("yyyy-mm- dd");
        calendar cal = calendar.getinstance(); 
        cal.settime(sdf.parse(smdate)); 
        long time1 = cal.gettimeinmillis ();              
        cal.settime(sdf.parse(bdate)); 
        long time2 = cal.gettimeinmillis ();      
        long between_days=(time2-time1)/ (1000*3600*24);

       return integer.parseint(string.valueof (between_days));  
    }
}
 


例3
复制代码 代码如下:

//取得剩余天数
   simpledateformat df=new simpledateformat("yyyymmdd");
   date d0=new java.util.date();
   date d1=df.parse(end_date);
   long time0=d0.gettime();
   long time1=d1.gettime();
   system.out.println((time1-time0)/(1000*60*60*24));

这样算两个时间相差的天数比较好
复制代码 代码如下:

/**
     * 计算两个日期之间相差的天数
     *
     * @param date1
     * @param date2
     * @return
     */
    public static int diffdates(date date1, date date2) {
        int result = 0;
        elapsedtime et = new elapsedtime();
        gregoriancalendar gc1 = new gregoriancalendar ();
        gregoriancalendar gc2 = new gregoriancalendar ();
        gc1.settime(date1);
        gc2.settime(date2);
        result = et.getdays(gc1, gc2);
        return result;
    } 

然后elapsetime中的方法是:
复制代码 代码如下:

public int getdays(gregoriancalendar g1, gregoriancalendar g2) {
  int elapsed = 0;
  gregoriancalendar gc1, gc2;
  if (g2.after(g1)) {
   gc2 = (gregoriancalendar) g2.clone();
   gc1 = (gregoriancalendar) g1.clone();
  } else {
   gc2 = (gregoriancalendar) g1.clone();
   gc1 = (gregoriancalendar) g2.clone();
  }
  gc1.clear(calendar.millisecond);
  gc1.clear(calendar.second);
  gc1.clear(calendar.minute);
  gc1.clear(calendar.hour_of_day);
  gc2.clear(calendar.millisecond);
  gc2.clear(calendar.second);
  gc2.clear(calendar.minute);
  gc2.clear(calendar.hour_of_day);
  while (gc1.before(gc2)) {
   gc1.add(calendar.date, 1);
   elapsed++;
  }
  return elapsed;
}
 

其实使用joda最简单
复制代码 代码如下:

public boolean isrentaloverdue(datetime datetimerented) {
  period rentalperiod = period.days(2);
  return datetimerented.plus(rentalperiod).isbeforenow()
}
 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网