减去两个日期会出现错误“操作符 - 参数类型未定义java.util.Date,java.util.Date”

时间:2014-07-22 12:53:45

标签: java date

在下面的代码中

  1. 日期中减去日期,发出此错误"The operator - is undefined for the argument type(s) java.util.Date, java.util.Date"
  2. 变量 currentDate String;为什么我无法将其保存在Date变量中,如Date currentDate = ddmmyy.format(new Date());.format函数是否返回String

    public class AgeCalculator {
    
      public static SimpleDateFormat ddmmyy=new SimpleDateFormat("dd/mm/yyyy");
    
    public static void main(String[] args) throws Exception {
    String dob = "05/01/1993";
    Date mod_date =  ddmmyy.parse(dob);
    String currentDate = ddmmyy.format(new Date());
    Date mod_currentDate = ddmmyy.parse(currentDate);
    int days = mod_currentDate-mod_date;
    
     }
    
    
    }
    

2 个答案:

答案 0 :(得分:1)

首先将dd/mm/yyyy改为dd/MM/yyyy作为mm - 以小时为单位的分钟和MM - 一年中的月份

SimpleDateFormat ddmmyy=new SimpleDateFormat("dd/MM/yyyy");
String dob = "21/07/2014";
Date mod_date =  ddmmyy.parse(dob);
String currentDate = ddmmyy.format(new Date());
Date mod_currentDate = ddmmyy.parse(currentDate);

它将以毫秒为单位给出它们之间的差异,其类型为long

long differenceInMillis = mod_currentDate.getTime()-mod_date.getTime();

从毫秒获得天数

int days = (int) (differenceInMillis / (1000*60*60*24));
System.out.println(days);

答案 1 :(得分:0)

另外看看这里; Java, Calculate the number of days between two dates
你的mod_currentDate返回1月22日而不是7月,因为你使用的是mm而不是MM。

public class AgeCalculator  {
     public static SimpleDateFormat ddmmyy=new SimpleDateFormat("dd/MM/yyyy");

      public static void main(String[] args) throws Exception {
      String dob = "05/01/1993";
      Date mod_date =  ddmmyy.parse(dob);
      Date currentDate = new Date();
      int days = daysBetween(mod_date,currentDate);
      System.out.println("Get the amount of days between " + mod_date + " and " + currentDate);
      System.out.println("Days= "+ days); 
       }

      public static int daysBetween(Date d1, Date d2){
        return (int)( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
    }
}

输出结果为:

Get the amount of days between Tue Jan 05 00:00:00 CET 1993 and Tue Jul 22 16:19:02 CEST 2014
Days= 7868