[java] How to tackle daylight savings using TimeZone in Java

I have to print the EST time in my Java application. I had set the time zone to EST using:

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("EST"));

But when the daylight savings is being followed in this timezone, my code does not print the correct time (it prints 1 hour less).

How to make the code work to read the correct time always, irrespective of whether the daylight savings are being observed or not?

PS: I tried setting the timezone to EDT, but it doesn't solve the problem.

This question is related to java date calendar timezone

The answer is


Instead of entering "EST" for the timezone you can enter "EST5EDT" as such. As you noted, just "EDT" does not work. This will account for the daylight savings time issue. The code line looks like this:

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("EST5EDT"));

public static float calculateTimeZone(String deviceTimeZone) {
    float ONE_HOUR_MILLIS = 60 * 60 * 1000;

    // Current timezone and date
    TimeZone timeZone = TimeZone.getTimeZone(deviceTimeZone);
    Date nowDate = new Date();
    float offsetFromUtc = timeZone.getOffset(nowDate.getTime()) / ONE_HOUR_MILLIS;

    // Daylight Saving time
    if (timeZone.useDaylightTime()) {
        // DST is used
        // I'm saving this is preferences for later use

        // save the offset value to use it later
        float dstOffset = timeZone.getDSTSavings() / ONE_HOUR_MILLIS;
        // DstOffsetValue = dstOffset
        // I'm saving this is preferences for later use
        // save that now we are in DST mode
        if (timeZone.inDaylightTime(nowDate)) {
            Log.e(Utility.class.getName(), "in Daylight Time");
            return -(ONE_HOUR_MILLIS * dstOffset);
        } else {
            Log.e(Utility.class.getName(), "not in Daylight Time");
            return 0;
        }
    } else
        return 0;
}

Implementing the TimeZone class to set the timezone to the Calendar takes care of the daylight savings.

java.util.TimeZone represents a time zone offset, and also figures out daylight savings.

sample code:

TimeZone est_timeZone = TimeZoneIDProvider.getTimeZoneID(TimeZoneID.US_EASTERN).getTimeZone();
Calendar enteredCalendar = Calendar.getInstance();
enteredCalendar.setTimeZone(est_timeZone);

private static Long DateTimeNowTicks(){
    long TICKS_AT_EPOCH = 621355968000000000L;
    TimeZone timeZone = Calendar.getInstance().getTimeZone();
    int offs = timeZone.getRawOffset();
    if (timeZone.inDaylightTime(new Date()))
        offs += 60 * 60 * 1000;
    return (System.currentTimeMillis() + offs) * 10000 + TICKS_AT_EPOCH;
}

In java, DateFormatter by default uses DST,To avoid day Light saving (DST) you need to manually do a trick,
first you have to get the DST offset i.e. for how many millisecond DST applied, for ex somewhere DST is also for 45 minutes and for some places it is for 30 min
but in most cases DST is of 1 hour
you have to use Timezone object and check with the date whether it is falling under DST or not and then you have to manually add offset of DST into it. for eg:

 TimeZone tz = TimeZone.getTimeZone("EST");
 boolean isDST = tz.inDaylightTime(yourDateObj);
 if(isDST){
 int sec= tz.getDSTSavings()/1000;// for no. of seconds
 Calendar cal= Calendar.getInstance();
 cal.setTime(yourDateObj);
 cal.add(Calendar.Seconds,sec);
 System.out.println(cal.getTime());// your Date with DST neglected
  }

As per this answer:

TimeZone tz = TimeZone.getTimeZone("EST");
boolean inDs = tz.inDaylightTime(new Date());

Other answers are correct, especially the one by Jon Skeet, but outdated.

java.time

These old date-time classes have been supplanted by the java.time framework built into Java 8 and later.

If you simply want the current time in UTC, use the Instant class.

Instant now = Instant.now();

EST is not a time zone, as explained in the correct Answer by Jon Skeet. Such 3-4 letter codes are neither standardized nor unique, and further the confusion over Daylight Saving Time (DST). Use a proper time zone name in the "continent/region" format.

Perhaps you meant Eastern Standard Time in east coast of north America? Or Egypt Standard Time? Or European Standard Time?

ZoneId zoneId = ZoneId.of( "America/New_York" );
ZoneId zoneId = ZoneId.of( "Africa/Cairo" );
ZoneId zoneId = ZoneId.of( "Europe/Lisbon" );

Use any such ZoneId object to get the current moment adjusted to a particular time zone to produce a ZonedDateTime object.

ZonedDateTime zdt = ZonedDateTime.now( zoneId ) ;

Adjust that ZonedDateTime into a different time zone by producing another ZonedDateTime object from the first. The java.time framework uses immutable objects rather than changing (mutating) existing objects.

ZonedDateTime zdtGuam = zdt.withZoneSameInstant( ZoneId.of( "Pacific/Guam" ) ) ;

Table of date-time types in Java, both modern and legacy.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to calendar

Moment.js get day name from date HTML Input Type Date, Open Calendar by default Check if a given time lies between two times regardless of date Creating java date object from year,month,day How to set time to 24 hour format in Calendar How to get Month Name from Calendar? Get first date of current month in java Specify the date format in XMLGregorianCalendar Getting last day of the month in a given string date How to change TIMEZONE for a java.util.Calendar/Date

Examples related to timezone

How to set the timezone in Django? How to convert Moment.js date to users local timezone? What does this format means T00:00:00.000Z? How do I get the current timezone name in Postgres 9.3? MySQL JDBC Driver 5.1.33 - Time Zone Issue Python get current time in right timezone Symfony2 and date_default_timezone_get() - It is not safe to rely on the system's timezone settings PHP date() with timezone? How to store a datetime in MySQL with timezone info Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST