I wrote a java utility function to convert yyyy/mm/dd as follows
public static long gettimestamp(String dateString) {
SimpleDateFormat df = new SimpleDateFormat("yyyy/mm/dd");
Date date;
try {
date = df.parse(dateString);
} catch (java.text.ParseException e) {
return 0;
}
long epoch = date.getTime();
return (epoch / 1000);
}
On passing 2014/06/12 - it gives 1389465360 (=Jan 11, 2014) which is wrong. Am I passing format in wrong way ?
You should uppercase the M. Lowercase m stands for minutes, while uppercase stands for month. Here's the documentation.
tl;dr
LocalDate.parse("2014/06/12".replace("/" , "-"))
.atStartOfDay(ZoneId.of("America/Montreal"))
.toEpochSecond()
Details
The Answer by Cornelissen is correct, your formatting pattern is incorrect.
Time zone
You fail to consider time zone. Your goal is getting a count of the seconds since the epoch of the start of 1970. That involves a time-of-day, when the day starts. The start of day varies around the globe by zone. A new day dawns earlier in Paris France than Montréal Québec.
Avoid old date-time classes
Furthermore, you are using troublesome old legacy date-time classes now supplanted by the java.time classes.
Use java.time
The LocalDate class represents a date-only value without time-of-day and without time zone.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu/mm/dd" );
LocalDate ld = LocalDate.parse( "2014/06/12" , f );
Alternatively, you could transform your input String to comply with standard ISO 8601 format by replacing the slash character with hyphen character. The java.time classes use ISO 8601 formats by default when parsing/generating strings.
Adjust that LocalDate into a specific time zone intended by the context of your date. We get a ZonedDateTime object.
Let java.time determine the start time of the day. Do not hard-code 00:00:00. In some time zones anomalies such as Daylight Saving Time (DST) may result in a day starting at a time such as 01:00:00.
ZoneId z = ZoneId.of( "America/Montreal" ); // Or ZoneOffset.UTC if you meant UTC (GMT).
ZonedDateTime zdt = ld.atStartOfDay( z );
You may interrogate for the number of whole seconds since the epoch of 1970-01-01T00:00:00Z.
long secondsSinceEpoch = zdt.toEpochSecond();
1402545600
Avoid using count-from-epoch
By the way, I strongly recommend against tracking date-time values as a count-since-epoch. Hard to read, hard to debug, prone to errors, leads to ambiguity over different epochs used by different software systems (at least a couple dozen epochs have been used).
Case in point: Your expected value of 1389465360 makes no sense to me. Using ZoneOffset.UTC I get the start of that date as 1402531200. Your expected value results in a time-of-day of 18:36 on January 11, 2014 when interpreted as a count of whole seconds since start of 1970 in UTC.
System.out.println ( Instant.ofEpochSecond ( 1_389_465_360L ).toString () );
2014-01-11T18:36:00Z
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
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.
Related
import java.text.SimpleDateFormat;
import java.util.Date;
import java.text.DateFormat;
import groovy.time.TimeCategory
def startDate = 'Monday, May 11 2015'
def today = new Date().format( 'EEEE, MMM dd yyyy' )
def today1 = quantityService.normalizeAndFormat(today, DatumType.DATE,
Formatters.DATE_IN_WORDS)
def diff = today1.minus(startDate);
The startDate is a string extracted from the database. And is formatted exactly like today1 is formatted above to produce 'Monday, May 11 2015'. I am unable to perform the subtract operation to obtain the value of the variable diff. Can you please guide me on how can I obtain the value of diff in the same format like startDate? Currently, the operation doesn't work probably because startDate is a string and today1 is a date object.
tl;dr
Use modern java.time classes, not the terrible legacy classes. Never use Date or DateFormat or SimpleDateFormat.
Example code in Java syntax:
Period
.between(
LocalDate.parse(
"Monday, May 11 2015" ,
DateTimeFormatter.ofPattern( "EEEE, MMM d uuuu" , Locale.US )
) ,
LocalDate.now( ZoneId.of( "America/Los_Angeles" ) )
)
.toString() ;
P3Y8M18D
Avoid legacy date-time classes
You are using terrible date-time classes that were obsoleted years ago by the java.time classes, with the adoption of JSR 310.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-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( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
DateTimeFormatter
Define a formatting pattern to match your input. (Java syntax)
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEEE, MMM d uuuu" , Locale.US ) ;
String input = "Monday, May 11 2015" ;
LocalDate ld = LocalDate.parse( input , f ) ;
ld.toString(): 2015-05-11
Elapsed time
To calculate elapsed time as years-months-days, use Period. For days (24-hour chunks of time, not calendar days), hours, and seconds, use Duration.
Period p = Period.between( ld , today ) ;
p.toString(): P3Y8M18D
That string in standard ISO 8601 formats means “three years, eight months, and eighteen days”.
See the above code run live at IdeOne.com.
There is no localization feature in java.time to represent a Period or Duration with words. Instead, you can generate your own string.
String output = p.getYears() + " years, " + p.getMonths() + " months, " + p.getDays() + " days" ; // Obviously, you could get fancier by checking for zero or singular values and then adjust the text.
ISO 8601
Avoid exchanging date-time values using localized formats such as that seen in your input. Instead, when exchanging date-time values as text, always use the standard ISO 8601 formats. They were wisely designed to avoid ambiguity. They are easy to parse by machine, and easy to read by humans across cultures.
The java.time classes use ISO 8601 formats by default when parsing/generating strings. So no need to specify any formatting pattern.
For a date-only value, the standard format is YYYY-MM-DD such as 2019-01-23.
LocalDate ld = LocalDate.parse( "2019-01-23" ) ;
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.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - 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
Most 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 (<26), 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.
My server is using GMT time zone but my application is working on IST, so I am converting GMT to IST while saving to database.But when I am converting this saved IST into epoch time then it's adding 5 hours 30 minutes into the saved IST time.
Is there any idea why? Am I doing anything wrong?
The code for converting GMT to IST:
public static Date convertGmtToIst(Date date) throws ParseException {
DateFormat converter = new SimpleDateFormat("dd-MM-yyyy:HH:mm:ss");
converter.setTimeZone(TimeZone.getTimeZone("IST"));
String dateReturns = converter.format(date);
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy:HH:mm:ss");
Date alteredDate = formatter.parse(dateReturns);
return alteredDate;
}
This is the code i am using to convert IST(2018-01-24 15:51:01) to epoch time.the date i am passing in this method is 2018-01-24 15:51:01 so this method should returns the epoch time of this date but it's adding 5 hours 30 minutes into this time.
public static long getEpochDateTime(Date date) {
long epochDateTime = date.getTime();
return epochDateTime;
}
tl;dr
Use smart objects, not dumb strings.
Instant.now().toEpochMilli()
Or:
myDate.toInstant().toEpochMilli()
Details
As discussed many times already on Stack Overflow…
My server is using GMT time zone
Never depend on the server OS settings for time zone. Always specify the optional time zone argument passed to the java.time classes’ methods.
converting GMT to IST while saving to database
Do most of your work in UTC. Adjust into another time zone only when business logic so dictates, or for presentation to user.
DateFormat converter = new SimpleDateFormat("dd-MM-yyyy:HH:mm:ss");
Work with date-time objects rather than mere strings.
Never use the troublesome Date and Calendar classes. Now supplanted by the java.time classes.
Never use 3-4 character pseudo-time zone codes such as IST. They are not true time zones, not standardized, and not even unique(!). Use true time zones in continent/region format.
ZoneId z = ZoneId.of( “Asia/Kolkata” ) ;
Get current moment in UTC.
Instant instant = Instant.now() ;
If your code must interoperate with Date, use new methods on old classes to convert to-and-fro.
Instant instant = myJavaUtilDate.toInstant() ;
Generate a string to represent this moment in standard ISO 8601 format by calling toString.
String output = instant.toString() ;
Adjust into another time zone. Same moment, same point on the timeline, different wall-clock time.
ZonedDateTime zdt = Instant.atZone( z ) ; // Same moment, different wall-clock time.
Call toString to generate a string with a format that wisely extends the ISO 8601 format by appending the name of the time zone in square brackets.
String output = zdt.toString() ;
To generate a string in other formats, see the DateTimeFormatter class.
You can move from a zoned moment to UTC by extracting an Instant.
Instant instant = zdt.toInstant() ;
returns the epoch time
Tracking time as a count-from-epoch is bad practice. But if you insist, you can extract a count of milliseconds from first moment of 1970 in UTC. Beware of data loss as Instant has a resolution of nanoseconds.
long millis = instant.toEpochMilli() ;
Get an Instant again. Again, I recommend against using a count-from-epoch, but if you insist.
Instant instant = Instant.ofEpochMilli( millis ) ;
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.
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.
You should probably include timezone when serializing the date.
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Why does java.util.Date object show date & time with respect to a timezone when in actuality, java.util.Date represents an instant on the time-line, not a "date"?
The actual data stored within the object is a long count of milliseconds since 1970-01-01T00:00Z (midnight at the start of 1970 GMT/UTC).
Also in docs, A java.util.Date instance has no concept of time-zone.
If so is the case, why does this snippet print date specifying timezone.
public static void main(String[] args) {
Date date = new Date();
System.out.println(date);
}
Output : Wed Mar 22 14:58:56 IST 2017
Why is it showing specific timezone in the output? I understand the SOP implements toString() internally. Does toString() effect the timezone?
Just follow the javadoc, as it says:
public String toString()
Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy
zzz is the time zone (and may reflect daylight saving time).
And when you dive into the source code, that this toString() implementation will at some point use TimeZone.getDefault()
( or to be precise: getDefaultRef()). In other words: the default implementation pulls in the "default" timezone of your JVM.
tl;dr
Current moment in UTC.
Instant.now() // Capture current moment in UTC.
.toString() // Generate String in standard ISO 8601 format.
2018-01-23T01:23:45.677340Z
Current moment in India time zone.
ZonedDateTime.now(
ZoneId.of( "Asia/Kolkata" )
).toString() // Generate string in format wisely extended from ISO 8601 standard, adding the time zone name in square brackets.
2018-01-23T06:53:45.677340+05:30[Asia/Kolkata]
Avoid legacy date-time classes
Why does java.util.Date object show date & time with respect to a timezone when in actuality, java.util.Date represents an instant on the time-line, not a "date"?
Because the java.util.Date and related classes (Calendar, SimpleDateFormat, and such) are poorly-designed. While a valiant effort at tackling the tricky subject of date-time handling, they fall short of the goal. They are riddled with poor design choices. You should avoid them, as they are now supplanted by the java.time classes, an enormous improvement.
Specifically to answer your question: The toString method of Date dynamically applies the JVM’s current default time zone while generating a String. So while the Date object itself represents a moment in UTC, the toString creates the false impression that it carries the displayed time zone.
Even worse, there is a time zone buried inside the Date object. That zone is used internally, yet is irrelevant to our discussion here. Confusing? Yes, yet another reason to avoid this class.
A java.util.Date instance has no concept of time-zone.
Not true. A Date represents a specific moment, a point on the timeline, with a resolution of milliseconds, in UTC. As you mention, it is defined as a count of milliseconds since the first moment of 1970 in UTC.
java.time
The java.time classes separate clearly the concepts of UTC, zoned, and unzoned values.
The java.time.Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction). This class replaces java.util.Date.
Instant instant = Instant.now() ; // Capture current moment in UTC.
Apply a time zone (ZoneId object) to an Instant and you get a ZonedDateTime object. That class replaces the java.util.Calendar class.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = instant.atZone( z ) ; // Same simultaneous moment as `instant`, but different wall-clock time.
If a value has only an offset-from-UTC but not a full time zone, use the OffsetDateTime class.
For a date only, without time-of-day and without time zone, use the LocalDate class. This class replaces the java.sql.Date class. Ditto for LocalTime replacing java.sql.Time.
LocalDate xmasDate2018 = LocalDate.of( 2018 , Month.DECEMBER , 25 ) ;
If the zone or offset are unknown or indeterminate, such as "Christmas starts at stroke of midnight on December 25, 2018", use the LocalDateTime class. This class does not represent an actual moment, a specific point on the timeline. This class lacks any concept of time zone or offset. So it can only represent potential moments along a range of about 26-27 hours.
LocalDateTime xmasEverywhere2018 = LocalDateTime.of( xmasDate2018 , LocalTime.MIN ) ;
Or…
LocalDateTime xmasEverywhere2018 = LocalDateTime.of( 2018 , Month.DECEMBER , 25 , 0 , 0 , 0 , 0 ) ;
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.
With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or 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.
It does have a concept of time zone, but it is always UTC. When it prints the date therefore there is no problem converting it to the time zone of your computer.
I'm trying to convert a string date "Sat Jan 25 00:13:31 +0000 2014"
to Unix Timestap using unix_timestamp() HiveQL function.
Convert time string with given pattern to Unix time stamp (in seconds),
return 0 if fail: unix_timestamp('2009-03-20', 'yyyy-MM-dd') = 1237532400
Java Doc
http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html#month
unix_timestamp("Jan-2014","MMM-yyyy") in Hive returns NULL
The function seems to work only with months expressed with an integer (ie MM).
Solutions?
Seems incredible but with other months except January (Jan) it works...
unix_timestamp('Feb 1 18:41:57 +0000 2014','MMM dd HH:mm:ss Z yyyy')
==> 1391280117
the EEE pattern for day of week doesn't work...
Solved, the problem was the localization of my linux System.
Using java.time
On the Java side, parse using java.time classes. The YearMonth class represents, well, a year and a month.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMM-yyyy" );
YearMonth ym = YearMonth.parse( "Jan-2014" , f );
We can get the first day of the month from that, to get a LocalDate.
LocalDate today = ym.atDay( 1 );
If you want a date-only value for Hive, you feed a string in standard SQL format. For a date-only value, SQL format coincides with ISO 8601 format. The java.time classes use standard ISO 8601 formats by default when parsing or generating strings.
String output = today.toString(); // YYYY-MM-DD format per ISO 8601 standard.
From there you apparently want a date-time value. We can arbitrarily assign the first moment of the day. The meaning of a date and determining the first moment depends on a time zone. For any given moment, the date and time-of-day vary around the globe by time zone.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = today.atStartOfDay( z );
From that you can generate a number of whole seconds since the epoch of beginning of 1970 in UTC (1970-01-01T00:00:00Z) to feed to Hive.
long secondsSinceEpoch = zdt.toEpochSecond();
1388534400
Going the other direction, you will need to go through the Instant class. 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.ofEpochSecond( 1_388_534_400L );
Apply a time zone if you want to view the wall-clock time of some region.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
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.
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?
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()
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.
I suggest to add summer/winter time offset to getRawOffset:
TimeZone tz1 = TimeZone.getTimeZone("GMT");
TimeZone tz2 = TimeZone.getTimeZone("America/New_York");
long timeDifference = tz1.getRawOffset() - tz2.getRawOffset() + tz1.getDSTSavings() - tz2.getDSTSavings();
I see this is an old thread - but adding this since I had a similar requirement recently -
This gives the actual difference in millis based on the CURRENT time(millis from epoch).
TimeZone.getTimeZone("America/New_York").getOffset(Calendar.getInstance().getTimeInMillis())
public String timeZone(Date date) {
TimeZone timeZone = TimeZone.getTimeZone("America/New_York");
long millis = timeZone.getRawOffset() + (timeZone.inDaylightTime(date) ? timeZone.getDSTSavings() : 0);
return String.format("%s%s:%s",
millis < 0 ? "-" : "+",
String.format("%02d", Math.abs(TimeUnit.MILLISECONDS.toHours(millis))),
String.format("%02d", Math.abs(TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis))))
);
}