0

I want difference between two dates i.e from gsp form and current date. From gsp date format is in form 1994-05-19 00:00:00.0 while I am using new Date() for current date it gives date in format of Sun Feb 28 07:42:13 NPT 2016. How could i get difference between these date. My code is:

int getAge(Date dateOfBirth){
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd")

    print(">>>><><><><<<<<<<<<<<<><><><><><><><><")
    print("date of birth");
    print(dateOfBirth)
    print(">>>><><><><<<<<<<<<<<<><><><><><><><><")
    print("current date")
    print(new Date())
    print(">>>><><><><<<<<<<<<<<<><><><><><><><><")

    Date currentDate = new Date()
    def cd = dateFormat.format(currentDate)

    String date = dateFormat.format(dateOfBirth)

    return 5;
}

I am using java 7 and grails 2.3.5

Madan
  • 380
  • 1
  • 4
  • 11
  • There are really two questions here: Parsing the dates and calculating the difference. The second question was answered, but not the first. Before you can compare the dates you need to be able to parse them to Date objects, not Strings. Here's how to parse them: `Date date1 = Date.parse('yyyy-MM-dd HH:mm:ss.S', '1994-05-19 00:00:00.0')` and `Date date2 = Date.parse('EEE MMM dd HH:mm:ss zzz yyyy', 'Sun Feb 28 07:42:13 NPT 2016')` – Emmanuel Rosa Feb 28 '16 at 03:31

1 Answers1

2

You can get the difference between two dates by simply subtracting the Unix epoch value of both dates:

date1.getTime() - date2.getTime()

This will give you the difference in milliseconds, which you can convert to whatever time unit you want. The sign of the result indicates which date came first, i.e. if negative, date1 occurred before date2.

Edit: I saw that your methods is looking for the age, using the same logic you can use: date1.getYear() - date2.getYear()

Maljam
  • 6,244
  • 3
  • 17
  • 30