当前位置: 移动技术网 > IT编程>开发语言>Java > Java判断两个日期相差天数的方法

Java判断两个日期相差天数的方法

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

本文实例讲述了java判断两个日期相差天数的方法。分享给大家供大家参考。具体如下:

import java.util.calendar;
public class datedifferent{
 public static void main(string[] args){
 calendar calendar1 = calendar.getinstance();
 calendar calendar2 = calendar.getinstance();
 calendar1.set(2007, 01, 10);
 calendar2.set(2007, 07, 01);
 long milliseconds1 = calendar1.gettimeinmillis();
 long milliseconds2 = calendar2.gettimeinmillis();
 long diff = milliseconds2 - milliseconds1;
 long diffseconds = diff / 1000;
 long diffminutes = diff / (60 * 1000);
 long diffhours = diff / (60 * 60 * 1000);
 long diffdays = diff / (24 * 60 * 60 * 1000);
 system.out.println("\nthe date different example");
 system.out.println("time in milliseconds: " + diff + " milliseconds.");
 system.out.println("time in seconds: " + diffseconds + " seconds.");
 system.out.println("time in minutes: " + diffminutes + " minutes.");
 system.out.println("time in hours: " + diffhours + " hours.");
 system.out.println("time in days: " + diffdays + " days.");
 }
}

把上面的代码放在项目里使用了一下,【求日期部分】是要满24小时才算一天的,不太适应项目的需求,故改成这样子。

/**
 * 得到两个日期相差的天数
 */
public static int getbetweenday(date date1, date date2) {
  calendar d1 = new gregoriancalendar();
  d1.settime(date1);
  calendar d2 = new gregoriancalendar();
  d2.settime(date2);
  int days = d2.get(calendar.day_of_year)- d1.get(calendar.day_of_year);
  system.out.println("days="+days);
  int y2 = d2.get(calendar.year);
  if (d1.get(calendar.year) != y2) {
//      d1 = (calendar) d1.clone();
    do {
      days += d1.getactualmaximum(calendar.day_of_year);
      d1.add(calendar.year, 1);
    } while (d1.get(calendar.year) != y2);
  }
  return days;
}

希望本文所述对大家的java程序设计有所帮助。

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

相关文章:

验证码:
移动技术网