-4

In below code

  1. on subtracting date from a date giving this error "The operator - is undefined for the argument type(s) java.util.Date, java.util.Date"
  2. variable currentDate is a String; why I couldn't save it in Date variable like this
    Date currentDate = ddmmyy.format(new Date()); , does .format function returns 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;
    
     }
    
    
    }
    
paul
  • 4,333
  • 16
  • 71
  • 144

2 Answers2

2

First change dd/mm/yyyy to dd/MM/yyyy as mm-Minute in hour and MM-Month in year

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);

It shall give you difference between them in milliseconds and its type is long

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

fnally get the number of days from milliseconds

int days = (int) (differenceInMillis / (1000*60*60*24));
System.out.println(days);
SparkOn
  • 8,806
  • 4
  • 29
  • 34
0

Also have a look here; Java, Calculate the number of days between two dates
Your mod_currentDate returns the 22th of January instead of July because of the fact you use mm instead of 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));
    }
}

The output is:

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
Community
  • 1
  • 1
Kokkie
  • 546
  • 6
  • 15