java.time
Solution using java.time
, the modern date-time API:
The modern date-time API offers OffsetDateTime
to represent a date-time object with a timezone offset. It can be converted to Instant
which represents an instantaneous point on the timeline. An Instant
is independent of any timezone i.e. it has a timezone offset of +00:00
hours, designated as Z
in the ISO 8601 standards.
Instant#toEpochMilli
converts this instant to the number of milliseconds from the epoch of 1970-01-01T00:00:00Z. This value can be set into an object of GregorianCalendar
which will then represent the same moment.
Demo:
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDateTime = "Mon, 27 Oct 2008 08:33:29 -0700";
OffsetDateTime odt = OffsetDateTime.parse(strDateTime, DateTimeFormatter.RFC_1123_DATE_TIME);
System.out.println(odt);
// In case you want a time zone neutral object, convert to Instant
Instant instant = odt.toInstant();
System.out.println(instant);
// Edit: If the requirement is a GregorianCalendar having the offset from
// the string — typically for an old API not yet upgraded to java.time:
ZonedDateTime zdt = ZonedDateTime.parse(strDateTime, DateTimeFormatter.RFC_1123_DATE_TIME);
GregorianCalendar gc = GregorianCalendar.from(zdt);
System.out.println("As Date: " + gc.getTime());
System.out.println("Time zone ID: " + gc.getTimeZone().getID());
System.out.println("Hour of day: " + gc.get(Calendar.HOUR_OF_DAY));
// ...
}
}
Output:
2008-10-27T08:33:29-07:00
2008-10-27T15:33:29Z
As Date: Mon Oct 27 15:33:29 GMT 2008
Time zone ID: GMT-07:00
Hour of day: 8
Calling getTime()
on the GregorianCalendar
converts to a Date
(another old and error-prone class) which doesn’t have a time zone, so the offset is lost. Printing the time zone ID and the hour of day demonstrates that both offset and time of day are preserved in the GregorianCalendar
.
Learn more about the modern date-time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.