Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Calculating time zone difference

Tags:

java

timezone

dst

How do I get the time difference from GMT for a specific date and time zone in Java?

Determining whether a specific time zone is in DST is quite straight-forward:

boolean isIsraelInDST = TimeZone.getTimeZone("Israel").inDaylightTime(new Date());

How do I get the actual time difference?

like image 658
Adam Matan Avatar asked Apr 03 '13 13:04

Adam Matan


People also ask

How do you find the time difference between two time zones?

So if it is 12 noon at Greenwich (0 degree), it would be 12:04 pm at 1 degree meridian and so on. In India, the standard meridian is 82-and-half degree. So the time difference between Greenwich and India is 82.5 x 4, which is 330 minutes (5 hours 30 minutes).

How do you subtract time in Java?

minus(long amountTosubtract, TemporalUnit unit) Return value: This method returns LocalTime based on this LocalTime with the specified amount subtracted. Exception: This method throws following Exceptions: DateTimeException – if the subtraction cannot be made.

How do you calculate duration in Java?

Find the time difference between two dates in millisecondes by using the method getTime() in Java as d2. getTime() – d1. getTime(). Use date-time mathematical formula to find the difference between two dates.


2 Answers

Use TimeZone.getRawOffset(): Returns the amount of time in milliseconds to add to UTC to get standard time in this time zone. Because this value is not affected by daylight saving time, it is called raw offset.

If you want the offset including DST then you use TimeZone.getOffset(long date). You should provide the concrete date to the method, eg now - System.currentTimeMillis()

like image 120
Evgeniy Dorofeev Avatar answered Nov 12 '22 16:11

Evgeniy Dorofeev


tl;dr

ZoneId.of( "Pacific/Auckland" )   // Specify a time zone.
    .getRules()                   // Get the object representing the rules for all the past, present, and future changes in offset used by the people in the region of that zone.
    .getOffset( Instant.now() )   // Get a `ZoneOffset` object representing the number of hours, minutes, and seconds displaced from UTC. Here we ask for the offset in effect right now.
    .toString()                   // Generate a String in standard ISO 8601 format.

+13:00

For the first moment of a certain date.

ZoneId.of( "Pacific/Auckland" )
    .getRules()
    .getOffset( 
        LocalDate.of( 2018 , Month.AUGUST , 23 )          // Specify a certain date. Has no concept of time zone or offset.
        .atStartOfDay( ZoneId.of( "Pacific/Auckland" ) )  // Determine the first moment of the day on that date in that region. Not always `00:00:00` because of anomalies such as Daylight Saving Time.
        .toInstant()                                      // Adjust to UTC by extracting an `Instant`. 
    ) 
    .toString()

+12:00

Avoid legacy date-time classes

The other Answers are outmoded, as the TimeZone class is now legacy. This and other troublesome old date-time classes are supplanted by the java.time time classes.

java.time

Now we use ZoneId, ZoneOffset, and ZoneRules instead of the legacy TimeZone class.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;  

Fetch the rules for that zone.

ZoneRules rules = z.getRules() ;

Ask the rules if Daylight Saving Time (DST) is in effect at a certain moment. Specify the moment as an Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = Instant.now() ;  // Capture current moment in UTC.
boolean isDst = rules.isDaylightSavings( instant ) ;

How do I get the actual time difference?

Not sure what you mean, but I will guess you are asking for the offset-from-UTC in effect at that moment for than zone. An offset is a number of hours, minutes, and seconds displacement from UTC. We represent an offset using ZoneOffset class. A time zone is a history of past, present, and future changes in offset used by the people of a particular region. We represent a time zone using ZoneId class.

Because the offset may vary over time for a region, we must pass a moment when asking for an offset.

ZoneOffset offset = rules.getOffset( instant ) ;

Generate a String representing that offset in ISO 8601 standard format.

String output output = offset.toString() ;

You can ask for the offset as a total number of seconds.

int offsetInSeconds = offset.getTotalSeconds() ;

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.

Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor java.sql.* classes.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

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.

like image 30
Basil Bourque Avatar answered Nov 12 '22 16:11

Basil Bourque