Sivisha Shankar
Sivisha Shankar

Reputation: 11

Calculating days between two dates in java with time zone

As per this question, I have calculated the days between two dates in java. The program is below

SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
String inputString1 = "23 01 1997";
String inputString2 = "27 04 1997";

try {
    Date date1 = myFormat.parse(inputString1);
    Date date2 = myFormat.parse(inputString2);
    long diff = date2.getTime() - date1.getTime();
    System.out.println ("Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
} catch (ParseException e) {
    e.printStackTrace();
}

But I have got issues when the dates are in daylight saving time zone. Like EDT to EST. For example, when we calculate days between (MAR 01, 2017) to (MAR 30, 2017), the actual count should be 29 but the result of the above program is 28.

Upvotes: 1

Views: 2462

Answers (3)

Sharon Ben Asher
Sharon Ben Asher

Reputation: 14328

Using java 8 new Date Time APi

    import java.time.*;
    import java.time.temporal.*;

    ZonedDateTime z1 = date1.toInstant().atZone(ZoneId.systemDefault());
    ZonedDateTime z2 = date2.toInstant().atZone(ZoneId.systemDefault());
    long diff = ChronoUnit.DAYS.between(z1, z2);  // 29

Upvotes: 0

Anton Balaniuc
Anton Balaniuc

Reputation: 11739

You can use LocalDate for that:

System.out.println(
        Period.between(
                LocalDate.parse("2017-03-01"), 
                LocalDate.parse("2017-03-30")
        ).getDays()
); // 29

or using dd M yyyy format:

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd M yyyy");
LocalDate localDate = LocalDate.parse("01 03 2017",dateTimeFormatter);
LocalDate localDate1 = LocalDate.parse("30 03 2017",dateTimeFormatter);
System.out.println(Period.between(localDate,localDate1).getDays());

Upvotes: 2

PankajT
PankajT

Reputation: 145

Possibly what you need is to convert the dates into same timezone before you do a diff on it. The timezone code should look something like this -

myFormat.setTimeZone(TimeZone.getTimeZone("EST"));

Upvotes: -1

Related Questions