I was looking for a way to get current time in various timezones based on an user input. I know I could use Joda Time! but is that the only way?
Isn't there an option in Java for doing this? I tried the following code which gives the same output for all 3 sysouts.
Calendar pst = Calendar.getInstance(TimeZone.getTimeZone("PST"));
System.out.println("PST " + pst.getTime());
Calendar ist = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
System.out.println("IST " + ist.getTime());
Calendar utc = Calendar.getInstance(TimeZone.getTimeZone("Etc/UTC"));
System.out.println("UCT " + utc.getTime());
What am I missing here to get current time in other timezones?
Yes, that would show the same value in every case (or milliseconds apart) because the three calendars all refer to the same instant in time (execution time notwithstanding) and that's all that a java.util.Date represents. That's the result of Calendar.getTime().
However, the Calendar itself does know about time zones, and that will be reflected when you use Calendar.get etc. It will also be used when you use a SimpleDateFormat, where you can specify a particular time zone.
// Specify whatever format you want - bear in mind different locales etc
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
format.setTimeZone(calendar.getTimeZone());
String text = format.format(calendar.getTime());
It's not clear exactly what you're trying to do, but basically you need to be aware of which types are time zone aware, and which aren't. It's really important to understand that a java.util.Date doesn't have a format, a calendar system or a time zone: it's just the number of milliseconds since the Unix epoch.
As Jon pointed out the method getTime() is returning a java.util.Date object which is just a millisecond value and not timezone aware.
If you are just looking at printing the times then you can use the calendar and manually get the fields you want like
System.out.println(utc.get(Calendar.HOUR_OF_DAY) + ":" + utc.get(Calendar.MINUTE))
This would need some formatting for a minute < 10 to display the 0
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time, the modern Date-Time API:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
Instant now = Instant.now();
System.out.println(now);
ZonedDateTime zdtLos = now.atZone(ZoneId.of("America/Los_Angeles"));
ZonedDateTime zdtIndia = now.atZone(ZoneId.of("Asia/Kolkata"));
ZonedDateTime zdtUtc = now.atZone(ZoneOffset.UTC);
System.out.println(zdtLos);
System.out.println(zdtIndia);
System.out.println(zdtUtc);
}
}
Output from a sample run:
2021-07-26T12:39:17.413671-07:00[America/Los_Angeles]
2021-07-27T01:09:17.413671+05:30[Asia/Kolkata]
2021-07-26T19:39:17.413671Z
ONLINE DEMO
An Instant represents an instantaneous point on the timeline, normally represented in UTC time. The Z in the output is the timezone designator for a zero-timezone offset. It stands for Zulu and specifies the Etc/UTC timezone (which has the timezone offset of +00:00 hours).
For any reason, if you need to convert this object of Instant to an object of java.util.Date, you can do so as follows:
Date date = Date.from(instant);
Learn more about the modern Date-Time API from Trail: Date Time.
Never use the 3-letter abbreviated timezone ID
Given below is an excerpt from the documentation page of TimeZone:
For compatibility with JDK 1.1.x, some other three-letter time zone
IDs (such as "PST", "CTT", "AST") are also supported. However, their
use is deprecated because the same abbreviation is often used for
multiple time zones (for example, "CST" could be U.S. "Central
Standard Time" and "China Standard Time"), and the Java platform can
then only recognize one of them.
* 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.
Related
As an input I have a string which is a String in ISO 8601 to represent date. For example:
"2017-04-04T09:00:00-08:00"
The last part of String, which is "-08:00" denotes TimeZone Offset. I convert this string into a Calendar instance as shown below:
Calendar calendar = GregorianCalendar.getInstance();
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US).parse(iso8601Date);
calendar.setTime(date);
iso8601Date is "2017-04-04T09:00:00-08:00"
But this does not pick timezone and if I get timezone from Calendar instance, it gives currently set instance of the laptop and does not pick up timestamp from ISO 8601 String. I check for timezone via calendar instance as:
calendar.getTimeZone().getDisplayName()
Can someone show how to pick timezone also in the Calendar instance?
tl;dr
OffsetDateTime.parse( "2017-04-04T09:00:00-08:00" )
Details
The last part of String which is "-08:00" denotes TimeZone Offset.
Do not confuse offset with time zone.
The -08:00 represents an offset-from-UTC, not a time zone. A time zone is a history of various offsets used in the past, present, and future by the people of a particular region. A time zone is named with a continent, slash, and region such as America/Los_Angeles or Pacific/Auckland or Asia/Kolkata.
You are using troublesome old date-time classes now supplanted by the java.time classes. For Android, see the ThreeTen-Backport and ThreeTenABP projects.
Your input indicates only offset but not zone. So we parse as a OffsetDateTime.
OffsetDateTime odt = OffsetDateTime.parse( "2017-04-04T09:00:00-08:00" ) ;
If you are absolutely certain of the intended time zone, assign it.
ZoneId z = ZoneId.of( "America/Los_Angeles" ) ;
ZonedDateTime zdt = odt.atZoneSameInstant() ;
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
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
When you create a Calendar, it takes the JVM's default timezone. And when you parse a String to a Date, it just sets one value: the number of milliseconds since epoch (1970-01-01T00:00Z). A Date doesn't have any timezone information, just this milliseconds value. So you need to set the timezone in the calendar.
In your formatter, you're treating Z as a literal, because it's inside quotes ('Z'). This ignores the offset and gets the date in the JVM default timezone (which will have a different value if the corresponding offset is not -08:00).
In JDK >= 7, you can use the X pattern to parse the offset:
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX", Locale.US).parse(iso8601Date);
But this doesn't set the timezone in the calendar (it will still use the JVM's default). So, a "better" way is to strip the offset from the input and handle it separately:
Calendar calendar = GregorianCalendar.getInstance();
String iso8601Date = "2017-04-04T09:00:00-08:00";
// get the offset (-08:00)
String offset = iso8601Date.substring(19);
TimeZone tz = TimeZone.getTimeZone("GMT" + offset);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US);
// set the offset in the formatter
sdf.setTimeZone(tz);
// parse just date and time (without the offset)
Date date = sdf.parse(iso8601Date.substring(0, 19));
// set the offset in the calendar
calendar.setTimeZone(tz);
calendar.setTime(date);
With this, the calendar will have the offset -08:00 set. As #BasilBourque's answer already said, -08:00 is an offset, not a timezone (the TimeZone class treats offsets just like they were timezones, which is a workaround/bad design choice).
Java new Date/Time API
The old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues, and they're being replaced by the new APIs.
In Android you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. You'll also need the ThreeTenABP to make it work (more on how to use it here).
#BasilBourque's answer already tells you about OffsetDateTime. But to convert to a Calendar, you can use a org.threeten.bp.ZonedDateTime and convert it using the org.threeten.bp.DateTimeUtils class:
String iso8601Date = "2017-04-04T09:00:00-08:00";
ZonedDateTime zdt = ZonedDateTime.parse(iso8601Date);
Calendar cal = DateTimeUtils.toGregorianCalendar(zdt);
The calendar will be already set with the -08:00 offset.
If you want to get the timezone from the offset, I'm afraid it's not that simple. More than one timezone can use the same offset, so you can't know for sure which timezone to use (the best you can do is to get a list of possible candidates).
java.util.Date
Just a more detailed note about java.util.Date. This link explains a lot about it, so I really recommend you to read it.
As already said above, a Date has no timezone information. It just keeps the number of milliseconds since epoch (which is 1970-01-01T00:00Z, or January 1st 1970 at midnight in UTC).
This value is the same everywhere in the world. Example: at the moment I'm writing this, the millis value for the current time is 1504632865935. This number is the same for anyone in the world who gets the current time at the same instant I did, regardless of what timezone they're using.
What is different is the local date and time that corresponds to this millis value. In UTC, it corresponds to 2017-09-05T17:34:25.935Z, in New York, the date is the same (September 5th 2017) but the time is different (13:34), and in Tokyo is September 6th 2017 at 02:34 AM.
Although the Date object is the same (because its millis value is 1504632865935 for everyone), the corresponding date and time changes according to the timezone used.
People tend to think that a Date has a timezone because when printing it (with System.out.println or by loggging) or when inspecting in a debugger, it implicity uses the toString() method, and this converts the date to the JVM's default timezone (and it also prints the zone name). This gives the impression that a Date has a format and a timezone set to it, but it doesn't.
One Key understanding I want to share from Hugo's answer and my further search is following. Please correct me if I am wrong:
Date does not care about timezone. It represents milliseconds passed since epoch.
Regarding finding the Timezone from provided ISO 8061 format is there, Date class can not tell that and we have to use some alternate methods as specified by #Hugo and #Basil Bourque.
I have two related questions.
Assume a program running in (British Standard Time)BST generates a date time value for current time in UTC (YYYY-MM-DDTHH:MM:SS.SSSZ) format.
Also assume current time in London is 2016-06-01 12:33:54.
If the current time given by the program is 2016-06-01T11:33:54.000Z , is the program wrong?
How is summertime offset for BST noted in the corresponding time format for YYYY-MM-DDTHH:MM:SS.SSSZ
I assume YYYY-MM-DDTHH:MM:SS+0001. Am I correct ?
Firstly please have a read of the iso8601 information. It's becoming more common place to deal with times in different time zones (e.g. server time zone and client time zone) and the standard is really useful.
In particular please read about UTC or "Zulu" time here.
The program is correct, since the London time is one hour ahead of "UTC" time in summer
The trailing 'Z' is a short notation for UTC (Zulu). You could also write "+00:00" instead of 'Z'. The SS.SSS refer to seconds and milliseconds - not related to the time zone. In devnull's comment he shows you how to apply an offset for summer.
Edit:
There's been some discussion in the comments about whether iso8601 timezone includes timezone or not, and whether timezone will in fact be printed out.
This depends completely on the date/time implementation. If we are using SimpleDateFormat then timezone is supported and will be printed.
Here's a code example to illustrate
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(formatter.format(new Date()));
formatter.setTimeZone(TimeZone.getTimeZone("Europe/London"));
System.out.println(formatter.format(new Date()));
Output
2016-06-02T12:53:14.924Z
2016-06-02T13:53:14.925+01:00
Naturally, if you are using a different date/time library such as joda-time, then the implentation details will be different.
Edit: As #DerrylThomas pointed out with SimpleDateFormat wise to use lower case y for years - unless it's intended to use week year - explained in a bit of detail in another answer to a similar question https://stackoverflow.com/a/56911450.
if the current time given by the program is 2016-06-01T11:33:54.000Z ,
is the program wrong?
The format is correct and conforms to ISO 8601 but it does not represent Europe/London time. In London, in 2016, the DST started at Sunday, March 27, 1:00 am and ended at Sunday, October 30, 2:00 am and therefore a date-time representation for Europe/London during this time should have a timezone offset of +01:00 hours. The Z at the end specifies Zulu time which is UTC time and thus has a timezone offset of +00:00 hours. The same instant can be represented for Europe/London as 2016-06-01T12:33:54+01:00.
java.time
The java.util date-time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to java.time, the modern date-time API* .
Even Joda-Time should not be used anymore. Notice the following note at the Home Page of Joda-Time
Joda-Time is the de facto standard date and time library for Java
prior to Java SE 8. Users are now asked to migrate to java.time
(JSR-310).
java.time API is based on ISO 8601 and the date-time string, 2016-06-01T11:33:54.000Z can be parsed into java.time.ZonedDateTime and java.time.OffsetDateTime without needing a date-time parsing/formatting type.
Demo:
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
ZonedDateTime zdt = ZonedDateTime.parse("2016-06-01T11:33:54.000Z");
System.out.println(zdt);
ZoneId zoneId = ZoneId.of("Europe/London");
ZonedDateTime zdtInLondon = zdt.withZoneSameInstant(zoneId);
System.out.println(zdtInLondon);
}
}
Output:
2016-06-01T11:33:54Z
2016-06-01T12:33:54+01:00[Europe/London]
How to deal with Daylight Saving Time (DST)?
As mentioned earlier, the date-time string, 2016-06-01T11:33:54.000Z can also be parsed into java.time.OffsetDateTime without needing a date-time parsing/formatting type. However, OffsetDateTime has been designed to deal with a fixed timezone offset whereas ZonedDateTime has been designed to deal with a timezone and thus it take care of DST automatically. You can convert a ZonedDateTime to OffsetDateTime using ZonedDateTime#toOffsetDateTime if required.
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSS z", Locale.ENGLISH);
String strDateTime = "2016-03-01T11:33:54.000 Europe/London";
ZonedDateTime zdt = ZonedDateTime.parse(strDateTime, dtf);
System.out.println(zdt);
strDateTime = "2016-06-01T11:33:54.000 Europe/London";
zdt = ZonedDateTime.parse(strDateTime, dtf);
System.out.println(zdt);
}
}
Output:
2016-03-01T11:33:54Z[Europe/London]
2016-06-01T11:33:54+01:00[Europe/London]
Notice how the timezone offset has automatically changed from Z to 01:00 to reflect DST change. On the other hand,
import java.time.OffsetDateTime;
public class Main {
public static void main(String[] args) {
String strDateTime = "2016-03-01T11:33:54.000+01:00";
OffsetDateTime odt = OffsetDateTime.parse(strDateTime);
System.out.println(odt);
strDateTime = "2016-06-01T11:33:54.000+01:00";
odt = OffsetDateTime.parse(strDateTime);
System.out.println(odt);
}
}
Output:
2016-03-01T11:33:54+01:00
2016-06-01T11:33:54+01:00
In this case, you do not talk about a timezone (e.g. Europe/London); rather, you talk about a fixed timezone offset of +01:00 hours.
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.
Following code throws the exception when try to parse from the string (2011-12-08T02:01:02+01:00):
image.setLastUpdated(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz")
.parse(imageElement.getAttribute("lastUpdate")))
I have also tried the following format:
image.setLastUpdated(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.parse(imageElement.getAttribute("lastUpdate")));
But I get the same exception:
java.text.ParseException: Unparseable date: "2011-12-08T02:01:02+01:00"
at java.text.DateFormat.parse(DateFormat.java:357)
at com.discavo.ImportManagerGiata.parseImageXML(ImportManagerGiata.java:204)
You need X as the specifier for the UTC offset as it's in ISO-8601 format, as per the SimpleDateFormat documentation.
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX")
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time, the modern Date-Time API:
The modern Date-Time API is based on ISO 8601 and does not require using a DateTimeFormatter object explicitly as long as the Date-Time string conforms to the ISO 8601 standards. Your Date-Time string conforms to the ISO 8601 format.
Demo:
import java.time.Instant;
import java.time.OffsetDateTime;
public class Main {
public static void main(String[] args) {
OffsetDateTime odt = OffsetDateTime.parse("2011-12-08T02:01:02+01:00");
System.out.println(odt);
// ########### In case you need Instant ###########
Instant instant = odt.toInstant();
System.out.println(instant);
// Java-12 onwards, you can parse the ISO-8601 compliant Date-Time with timezone
// information directly into Instant
instant = Instant.parse("2011-12-08T02:01:02+01:00");
System.out.println(instant);
}
}
Output:
2011-12-08T02:01:02+01:00
2011-12-08T01:01:02Z
2011-12-08T01:01:02Z
ONLINE DEMO
An Instant represents an instantaneous point on the timeline in UTC. The Z in the output is the timezone designator for a zero-timezone offset. It stands for Zulu and specifies the Etc/UTC timezone (which has the timezone offset of +00:00 hours).
Note: For any reason, if you need to convert this object of Instant to an object of java.util.Date, you can do so as follows:
Date date = Date.from(instant);
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.
The answer by Jon Skeet is correct. But FYI…
No problem in Joda-Time
The problem presented by this question does not exist if using Joda-Time rather than the mess that is the java.util.Date/Calendar classes bundled with Java.
Joda-Time 2.3 has a variety of built-in parsers, so no need to specify a format in this case. Use methods on the ISODateTimeFormat class to retrieve a variety of formatters designed to parse variations of ISO 8601 formatted strings.
The question fails to account for time zone. So I am showing all three possibilities:
You want the time converted to a specific time zone.Denver in this example.
You want the time adjusted to UTC, for no time offset.Common for storage or further date-time work.
You want to preserve this date-time with its offset.Not usually a good idea, as you have neither the benefit of UTC (no offset and no need to worry about Daylight Saving Time DST or other issues), nor the benefit of a named time zone with rules to handle DST or other issues.
For Desired Time Zone
// For desired time zone. Arbitrarily using 'Denver' as named time zone for this example.
DateTimeZone denverTimeZone = DateTimeZone.forID( "America/Denver" );
org.joda.time.DateTime dateTimeInDenver = org.joda.time.format.ISODateTimeFormat.dateTimeNoMillis().withZone(denverTimeZone).parseDateTime( "2011-12-08T02:01:02+01:00" );
System.out.println( "dateTimeInDenver: " + dateTimeInDenver );
When run…
dateTimeInDenver: 2011-12-07T18:01:02.000-07:00
For UTC
// For UTC (no offset).
org.joda.time.DateTime dateTimeInUTC = org.joda.time.format.ISODateTimeFormat.dateTimeNoMillis().withZoneUTC().parseDateTime( "2011-12-08T02:01:02+01:00" );
System.out.println( dateTimeInUTC );
When run…
2011-12-08T01:01:02.000Z
For Offset As Parsed
// For offset as parsed.
// Least beneficial, as no rules for Daylight Saving Time (DST) or other anomalies can be applied.
org.joda.time.DateTime dateTimeWithOffsetParsed = org.joda.time.format.ISODateTimeFormat.dateTimeNoMillis().withOffsetParsed().parseDateTime( "2011-12-08T02:01:02+01:00" );
System.out.println( "dateTimeWithOffsetParsed: " + dateTimeWithOffsetParsed );
When run…
dateTimeWithOffsetParsed: 2011-12-08T02:01:02.000+01:00
I have some DateTime including TimeZone Europe/Vienna (+0200). It is fetched by this method:
settlementService.getPendingPeriodStart()
and look with toString like this:
2012-06-01T00:00:00.000+02:00
Now I want to save this date 2012-06-01 as java.util.Date, so I tried something like this:
transactionDate = settlementService.getPendingPeriodStart().withTime(0, 0, 0, 0).toDate();
But the result is this:
Thu May 31 22:00:00 UTC 2012
What's the best way to save the DateTime result as Date including the TimeZone offset, so transactionDate should be 2012-06-01. I could tinker with GregorianCalendar, but that's not what I like. This ought to be easier, isn't it?
By the way (if this isn't clear). The local system runs on UTC. That's why the result is Thu May 31 22:00:00 UTC 2012.
Unfortunately, the accepted answer is misguiding. As a matter of fact,
2012-06-01T00:00:00.000+02:00 = 2012-05-31T22:00:00Z
The Z on the right-hand side is the timezone designator for zero-timezone offset. It stands for Zulu and specifies the Etc/UTC timezone (which has the timezone offset of +00:00 hours).
Writing 2012-06-01T00:00:00.000+02:00 as 2012-06-01, although a matter of just a function call, is dangerous for any business logic that depends on the timezone because it may have a different date in a timezone with a different offset value e.g. as shown above. 2012-06-01 is just a LocalDate which should be used to track events like birth date, wedding date etc.
java.time
The legacy date-time API (java.util date-time types and their formatting type, SimpleDateFormat etc.) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time, the modern date-time API*.
Also, quoted below is a notice at the Home Page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
Solution using java.time, the modern API:
How to parse the given date-time string:
The given date-time string has a timezone offset and therefore it should be parsed to OffsetDateTime. Since the modern date-time API is based on ISO 8601 and does not require using a DateTimeFormatter object explicitly as long as the date-time string conforms to the ISO 8601 standards.
OffsetDateTime odt = OffsetDateTime.parse("2012-06-01T00:00:00.000+02:00"); // 2012-06-01T00:00+02:00
How to get the date-time out of it in UTC:
There are multiple ways. The simplest way is to convert it into an Instant which represents an instantaneous point on the timeline which is in UTC.
Instant instant = odt.toInstant(); // 2012-05-31T22:00:00Z
Alternatively,
OffsetDateTime odtUtc = odt.withOffsetSameInstant(ZoneOffset.UTC); // 2012-05-31T22:00Z
How to get java.util.Date out of it:
If at all, you need an instance of java.util.Date from the instance of OffsetDateTime, you can use Date#from(Instant instant).
Date date = Date.from(instant); // Thu May 31 23:00:00 BST 2012 <--In my timezone
Note that a java.util.Date object is not a real date-time object like the modern date-time types; rather, it represents the number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT (or UTC). When you print an object of java.util.Date, its toString method returns the date-time in the JVM's timezone, calculated from this milliseconds value. If you need to print the date-time in a different timezone, you will need to set the timezone to SimpleDateFormat and obtain the formatted string from it e.g.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
System.out.println(sdf.format(date)); // 2012-05-31T22:00:00.000Z
How to get the date part out of it:
As I have already explained, it is dangerous for any business logic that depends on the timezone. However, it's just a matter of a simple function call.
LocalDate localDate = odt.toLocalDate(); // 2012-06-01
Learn more about java.time, 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.
A date and the time zone of the user are 2 different things. One is a date, the other is a preference, or a presentation parameter.
Don't try to store them in the same field.
Consider that it wouldn't be even possible to store them together efficiently (without losing precision) as a date can be stored in a long only because it's specified that it's an UTC date.
You can save the time zone as an offset (a frequent recommendation is to keep the minutes in this offset ([hh]:[mm]) because of very small cases).
I think I found a solution. (If you know a better solution, just let me know)
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
DateTime dateTimeWithTimeZone = new DateTime(DateTimeZone.forID("Europe/Vienna")).withDate(2012, 06, 01).withTime(0, 0, 0, 0);
Date dateWithTimeZoneIncluded = dateTimeWithTimeZone.toLocalDate().toDate();
System.out.println(dateFormat.format(dateWithTimeZoneIncluded));
The result is 2012-06-01 as expected.
Can somebody please tell, what's the difference between the following two statements:
TimeZone.getTimeZone("America/New_York")
and
TimeZone.getTimeZone("EST")
In other words, why is EST different from America/New_York. Also in my application, to get the current time zone in US, should I use America/New_York or EST.
EST is UTC - 5 hours. America/New_York is EST in the winter and E*D*T in the summer, so right now New York is UTC - 4 hours.
EST is half of the New York time zone, effectively. It's always in standard time - it doesn't have the daylight saving part. It's not really a proper time zone in its own right, IMO - it's the "standard" part of a fuller time zone. When writing about a time zone which is just a fixed offset and not related to a particular place, I'd prefer to use "Etc/GMT+5" or something similarly obviously-fixed. (I don't generally like even "Eastern Time" and the like, as different places which observe "Eastern Time" may vary in their DST transitions. It's a bit like calling an encoding "extended ASCII"... it tells you some information, but not quite enough.)
So if you want to know the actual local time for New York at any particular instant, use America/New_York.
In general, stay away from the abbreviations. From the documentation:
For compatibility with JDK 1.1.x, some other three-letter time zone IDs (such as "PST", "CTT", "AST") are also supported. However, their use is deprecated because the same abbreviation is often used for multiple time zones (for example, "CST" could be U.S. "Central Standard Time" and "China Standard Time"), and the Java platform can then only recognize one of them.
(Personally I'd also advise you to stay away from Date and Calendar, preferring to use Joda Time wherever possible. That's a different matter though, really.)
The timezone, America/New_York observes two different timezone offsets:
EST (winter time): has a timezone offset of -05:00 hours
EDT (summer time): has a timezone offset of -04:00 hours
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice from the home page of Joda-Time:
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.
What Date-Time object should I use to adjust the offset automatically?
Use ZonedDateTime which has been designed to adjust the timezone offset automatically.
Demo:
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
ZoneId zoneId = ZoneId.of("America/New_York");
// Custom times
ZonedDateTime zdtDstOn = ZonedDateTime.of(LocalDate.of(2020, Month.OCTOBER, 22), LocalTime.MIN, zoneId);
ZonedDateTime zdtDstOff = ZonedDateTime.of(LocalDate.of(2020, Month.NOVEMBER, 22), LocalTime.MIN, zoneId);
System.out.println(zdtDstOn);
System.out.println(zdtDstOff);
// Current time
ZonedDateTime zdtNow = ZonedDateTime.now(zoneId);
System.out.println(zdtNow);
}
}
Output:
2020-10-22T00:00-04:00[America/New_York]
2020-11-22T00:00-05:00[America/New_York]
2021-08-17T12:19:41.854781-04:00[America/New_York]
ONLINE DEMO
Avoid using the abbreviated timezone names
The following quote from the documentation states the problem clearly:
Three-letter time zone IDs
For compatibility with JDK 1.1.x, some
other three-letter time zone IDs (such as "PST", "CTT", "AST") are
also supported. However, their use is deprecated because the same
abbreviation is often used for multiple time zones (for example, "CST"
could be U.S. "Central Standard Time" and "China Standard Time"), and
the Java platform can then only recognize one of them.
Then, what Date-Time object should I use for a fixed timezone offset?
Use OffsetDateTime for a fixed timezone offset.
Demo:
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Month;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
public class Main {
public static void main(String[] args) {
ZoneOffset zoneOffset = ZoneOffset.of("-04:00");
// A custom time
OffsetDateTime odt = OffsetDateTime.of(LocalDate.of(2020, Month.OCTOBER, 22), LocalTime.MIN, zoneOffset);
System.out.println(odt);
// Current time
OffsetDateTime odtNow = OffsetDateTime.now(zoneOffset);
System.out.println(odtNow);
}
}
Output:
2020-10-22T00:00-04:00
2021-08-17T12:36:09.123599-04:00
ONLINE DEMO
Note: For any reason, if you need to convert an object of OffsetDateTime or ZonedDateTime to an object of java.util.Date, you can do so as follows:
Date date = Date.from(odtNow.toInstant());
or
Date date = Date.from(zdtNow.toInstant());
Learn more about the modern Date-Time API* from Trail: Date Time.
Check this answer and this answer to learn how to use java.time API with JDBC.
* 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.