using date for calender as an input to figure out the time difference

124 Views Asked by At

I have the following code and trying to figure out if the date difference is greater than one year or not. If I have the two dates like this:

  1. 2022-08-20 10:26:44.000

  2. 2023-08-25 10:26:44.000

How should I send these two dates such that it's accepted for moreTheOneYearDifference method as defined below?

public class DateOneYearDifferenceTest {

    final GregorianCalendar gc = new GregorianCalendar();

    public static void main(String[] args) {
        System.out.printf(moreTheOneYearDifference(2022-08-20 10:26:44.000, 2023-08-25 10:26:44.000));
        

    }

    public boolean moreTheOneYearDifference(Calendar c1, Calendar c2) {
        int days = 365;
        if (c1.before(c2) && gc.isLeapYear(c1.get(Calendar.YEAR))) {
            days += 1;
        } else if (gc.isLeapYear(c2.get(Calendar.YEAR))) {
            days += 1;
        }
        return TimeUnit.MICROSECONDS.toDays((long) Math.abs(c1.getTimeInMillis() - c2.getTimeInMillis())) >= days;
    }

}

The above method was copied from this stackoverflow post answer

3

There are 3 best solutions below

14
Diego Borba On BEST ANSWER

How should I send these two dates such that it's accepted for moreTheOneYearDifference method as defined below?

You can send like this:

Calendar date1 = new GregorianCalendar(2022, 7, 20, 10, 26, 44); // Note: Month is 0-based
Calendar date2 = new GregorianCalendar(2023, 7, 25, 10, 26, 44); // Note: Month is 0-based

I corrected the month values to be 0-based (January is 0, February is 1, and so on), and created instances of Calendar for date1 and date2 using the GregorianCalendar class and provided the correct year, month, day, hour, minute, and second values.

Note: I think that you mean moreThanOneYearDifference and no moreTheOneYearDifference

how would I go about converting 2022-08-20 10:26:44.000 such that it fits this format Calendar date1 = new GregorianCalendar(2022, 7, 20, 10, 26, 44) ?

You can do this way:

DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");

Calendar c1 = new GregorianCalendar();
c1.setTimeInMillis(format.parse("2022-08-20 10:26:44.000").getTime());

Calendar c2 = new GregorianCalendar();
c2.setTimeInMillis(format.parse("2023-08-25 10:26:44.000").getTime());

But, like Basil Bourque said: "These terrible date-time classes were years ago supplanted by the modern java.time classes defined in JSR 310."

So, I recommend that you use the modern java.time classes if it is possible. It will be something like this:

public class DateOneYearDifferenceTest {
    public static void main(String[] args) {
        // Original Strings
        String dateString1 = "2022-08-20 10:26:44.000";
        String dateString2 = "2023-08-20 10:26:44.000";

        // Format parser
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");

        // Convertion
        LocalDateTime dateTime1 = LocalDateTime.parse(dateString1, formatter);
        LocalDateTime dateTime2 = LocalDateTime.parse(dateString2, formatter);

        if (moreThanOneYearDifference(dateTime1, dateTime2)) {
            System.out.println("The time difference is more than one year.");
        } else {
            System.out.println("The time difference is not more than one year.");
        }
    }

    /*
     * Modern method
     */
    public static boolean moreThanOneYearDifference(LocalDateTime dateTime1, LocalDateTime dateTime2) {
        long daysDifference = ChronoUnit.DAYS.between(dateTime1, dateTime2);
        return Math.abs(daysDifference) > 365;
    }
}

I don't know how much specific you need to be, so maybe you should edit it to consider hours, minutes, seconds, etc...

5
lzzgabriel On

Maybe try something like this:

DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
    
Calendar c1 = new GregorianCalendar(), c2 = new GregorianCalendar();
c1.setTimeInMillis(format.parse("2022-08-20 10:26:44.000").getTime());
c2.setTimeInMillis(format.parse("2023-08-25 10:26:44.000").getTime());
System.out.println(moreTheOneYearDifference(c1, c2));
5
deHaar On

Just as an alternative, you could calculate the Period.between(…) two LocalDates, which are part of a LocalDateTime, available by LocalDateTime.toLocalDate().

See this example:

public static void main(String[] args) {
    // example datetimes
    String a = "2022-08-20 10:26:44.000";
    String b = "2023-08-25 10:26:44.000";
    // prepare a formatter that is able to parse those Strings
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS");
    // then actually parsen them
    LocalDateTime ldtA = LocalDateTime.parse(a, dtf);
    LocalDateTime ldtB = LocalDateTime.parse(b, dtf);
    // caclulate the period between those two dates
    Period period = Period.between(ldtA.toLocalDate(), ldtB.toLocalDate());
    // check if the resulting period is a full year or more
    if (period.getYears() >= 1) {
        System.out.println("Difference is greater than or equals one year");
    } else {
        System.err.println("Difference is less than one year");
    }
}

Resulting output:

Difference is greater than or equals one year

Have a look at the other methods of a Period and if you want to involve time of day or calulate with that exclusively, check out a Duration:

The Java™ Tutorials — Period and Duration