Shi Tim
Shi Tim

Reputation: 453

Java how to calculate relative date and handle daylight saving at same time?

I want to calculate Relatives Date which is how many days different from 01/01/1957 to a given date. I need handle Daylight saving at the same time. Here is the code:

public String convertToRelative(String endDate) throws ParseException {

    String relativeDate;
    String baseDate = "19570101";
    boolean isDST = TimeZone.getDefault().inDaylightTime(new java.util.Date());

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

    Calendar cal = Calendar.getInstance();

    cal.setTime(sdf.parse(baseDate));

    long time1 = cal.getTimeInMillis();

    cal.setTime(sdf.parse(endDate));

    long time2 = cal.getTimeInMillis();


    if ( isDST ) {

        long between_days = (time2 - time1 - 3600000)/(1000*3600*24);

        int relative = Integer.parseInt(String.valueOf(between_days));

        relativeDate = String.valueOf(relative + 1);

    } else {

        long between_days = (time2 - time1)/(1000*3600*24);

        int relative = Integer.parseInt(String.valueOf(between_days));

        relativeDate = String.valueOf(relative + 1);

    }

    return relativeDate;

}

From the code, you can see I checked if the time is in daylight saving at:

boolean isDST = TimeZone.getDefault().inDaylightTime(new java.util.Date());

But it only gets default time from the system. My question is how can I check the given date is a daylight saving date first then do the calculation part. I'm using New Zealand time zone. Thank you.

Upvotes: 0

Views: 729

Answers (1)

Pallavi Sonal
Pallavi Sonal

Reputation: 3901

Rather than doing the calculations manually, you should try to take advantage of the built-in API of java.time which are easy to use and take care of DST for you. Refer : https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html#until-java.time.temporal.Temporal-java.time.temporal.TemporalUnit-

The following code should help you with calculations you are trying to do:

ZoneId auckZone = ZoneId.of("Pacific/Auckland");
LocalDateTime base = LocalDate.of(1957, 01, 01).atStartOfDay();
ZonedDateTime baseDate = base.atZone(auckZone);
ZonedDateTime endDate = LocalDate.parse(endDt, DateTimeFormatter.ofPattern("yyyyMMdd")).atStartOfDay().atZone(auckZone);
System.out.println(baseDate.until(endDate, ChronoUnit.DAYS));

Upvotes: 1

Related Questions