-1

I have date of birth of a person. There is one more date given say, d1. I want to know if the person reaches age 40 during last one year from d1 date. Date is in 'yyyyMMdd' format

I think of something related to finding out the time and do some subtraction and then check if it is 40 or not etc.

What is the best way to do this calculation?

halfer
  • 19,824
  • 17
  • 99
  • 186
Anand
  • 20,708
  • 48
  • 131
  • 198

4 Answers4

1

There are many ways how you can achieve this, from using milliseconds and simple substraction and conversion to years to using Calendar objects.

You also might want to have a look at joda-time (a handy 3rd party java api to handling with dates) and

Here is a way to do it using Calendar

@Test
public void compareDates() throws ParseException {
    Date d1 = new SimpleDateFormat("yyyyMMdd").parse("20130317");
    Date birthDate1 = new SimpleDateFormat("yyyyMMdd").parse("19700101");
    Date birthDate2 = new SimpleDateFormat("yyyyMMdd").parse("19900101");

    GregorianCalendar cd1 = new GregorianCalendar();
    cd1.setTime(d1);
    cd1.set(Calendar.YEAR, cd1.get(Calendar.YEAR)-1); // one year ago

    GregorianCalendar cbd1 = new GregorianCalendar();
    cbd1.setTime(birthDate1);

    GregorianCalendar cbd2 = new GregorianCalendar();
    cbd2.setTime(birthDate2);

    Assert.assertTrue((cd1.get(Calendar.YEAR) - cbd1.get(Calendar.YEAR)) > 40);
    Assert.assertFalse((cd1.get(Calendar.YEAR) - cbd2.get(Calendar.YEAR)) > 40);
}
A4L
  • 17,353
  • 6
  • 49
  • 70
  • FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html), and `java.text.SimpleTextFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [java.time](https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes. Likewise, the Joda-Time project is in maintenance mode, with the team advising migration to java.time. – Basil Bourque May 03 '17 at 09:44
0

getTime() will return the time in milliseconds.

long diff = d2.getTime() - d1.getTime(); // the difference in milliseconds

I'll leave it as a practice to convert these milliseconds into years.

poitroae
  • 21,129
  • 10
  • 63
  • 81
  • You downvoted, because? Please don't tell me because of the *exercise*. – poitroae Mar 18 '13 at 16:08
  • There are so many things you can do wrong when you do date calculations. Days, years are not always of the same length etc., so simply don't do it yourself. – keuleJ Apr 02 '13 at 10:32
0
public class DateTester{

    private static final long MILLISECONDS_IN_YEAR = 31556926279L;

    public static void main(String[] args) {
            //Note:  These constructors are deprecated
            //I'm just using them for a quick test

    Date startDate = new Date(2013,03,01);
    Date birthday = new Date(1981,01,1981);//Returns false
    Date birthday2 = new Date(1972,03,20); //Returns true
    Date birthday3 = new Date(1973,02,27); //Test edge cases  //Returns false
    Date birthday4 = new Date(1972,02,27); //Test edge cases, //Returns false


    System.out.println(withinYear(birthday, startDate,40));
    System.out.println(withinYear(birthday2, startDate,40));
    System.out.println(withinYear(birthday3, startDate,40));
    System.out.println(withinYear(birthday4, startDate,40));


        System.out.println(withinYear(birthday, startDate,40));
        System.out.println(withinYear(birthday2, startDate,40));
    }

    public static boolean withinYear(Date birthday, Date startDate, int years){
        if(birthday.before(startDate)){
            long difference = Math.abs(birthday.getTime() - startDate.getTime());
            int yearDifference = (int) (difference/MILLISECONDS_IN_YEAR);
            return yearDifference  < (years +1) && yearDifference >= years;
        }
        return false;
    }
}
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
0

Avoid legacy date-time classes

The other Answers use the troublesome old date-time classes that are now legacy, supplanted by the java.time classes.

Using java.time

The LocalDate class represents a date-only value without time-of-day and without time zone.

LocalDate birthDate = LocalDate.parse( "19540123" , DateTimeFormatter.BASIC_ISO_DATE ) ;
LocalDate d1 = LocalDate.parse( "20110317" , DateTimeFormatter.BASIC_ISO_DATE );

LocalDate dateWhen40YearsOld = birthDate.plusYears( 40 ) ;
Boolean turning40WithinYear = 
    ( ! dateWhen40YearsOld.isBefore( d1 ) )         // "If not before" is a short way of saying "is equal to or later than". 
    && 
    dateWhen40YearsOld.isBefore( d1.plusYears( 1 ) )
;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154