Time Zones in Java / GWT (Client-side) - java

[Client-side GWT class]
I have a Date Object...
Date dataObject = DateTimeFormat.getFormat("yyyy-MM-dd'T'HH:mm:ss.SSS")
.parse("2009-10-12T00:00:00.000);
This works fine. However when I do a:
dateObject.getTime();
It returns a UNIX Time milliseconds using a GMT with daylight savings, therefore making it a UNIX Time I cannot use. I need it in UTC. How do I do this?
Currently I'm parsing a date and it is giving me back:
'Thu Apr 16 08:46:20 GMT+100 2009' # '1239867980191'
However the date I'm passing in is 1 hour less than this time (7:46 and not 8:46!).
How do I pass in the fact it's UTC? Or if it can't use UTC (which would be ridiculous), how do I use GMT without the daylight savings?

Your last edit makes things clearer.
Basically, you are confused, and you already get what you want.
1239867980191 milliseconds since the Epoch translates to Thursday, April 16th, 2009, at 7:46:20.191 in the GMT time zone. The very same instant translates to the same day, but 8:46:20.191 in the GMT+01 time zone. If your input string specified "7:46:20.191" and you indeed got 1239867980191 from Date.getTime() then congratulations, the parsing code understood your "7:46:20.191" as to be interpreted in the GMT time zone, and did it properly.
If afterwards you get "8:46:20" when printing, this is only because you use the GMT+01 time zone for displaying that instant. Note that the string contains GMT+100 precisely to notify you that it uses that time zone for display purposes. The instant which the Date instance represents is nonetheless exactly the instant you wish it to contain. Remember that a Date instance represents an instant in time, for which no notion of time zone applies: time zones are used to convert instants into calendar elements (days, hours...) and back.
To convert a Date to a displayable string, use DateTimeFormat.format(Date, TimeZone) which lets you specify which time zone you want to use for that string.

Since the Calendar class is not supported in GWT, maybe something hackish like this will work:
final String timezone = "GMT-07:00";
DateTimeFormat dtf = DateTimeFormat.getFormat("yyyy-MM-dd'T'HH:mm:ssZZZZ");
long unix = dtf.parse("2009-10-12T00:00:00" + timezone).getTime();
This way you can provide the correct timezone info - though, that should be the default behaviour.

It is the other way round. A Date instance holds the time in milliseconds since the Epoch, using the UTC time scale (i.e. leap seconds are ignored). This is what Date.getTime() returns and that's what you want.
The culprit here is the parser, which interprets the date you give as a string in your local time zone. If you want DateTimeFormat to interpret the string as a date-and-time given in the UTC time zone, append an explicit time zone to the parsed string:
DateTimeFormat.getFormat("yyyy-MM-dd'T'HH:mm:ssZZZZ")
.parse("2009-10-12T00:00:00.000" + " GMT");
(The above assumes that I understood GWT documentation properly; I have not tried.)
Just to be clear in my notations: for all practical purposes, there is no difference between "GMT" and "UTC", and there is no daylight saving in the GMT time zone. Other time zones are often defined as "GMT plus or minus some offset" and the offset may change between summer and winter. For instance, the time zone in New York is somewhat equivalent to "GMT-04" in summer and "GMT-05" in winter.

I keep seeing formats with ZZZZ being suggested... but why?
"yyyy-MM-dd'T'HH:mm:ss.SSSZ" would match
"2009-10-12T00:00:00.000-0000"
The last part being the offset from UTC; California (to use someone else's example time) would be -0800, -0700 in summer.
As a side note, GMT is also always -0000. That's why Britain's summer time zone is BST (British Summer Time, +0100).

Try the Calendar object.
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
Date dataObject = DateTimeFormat.getFormat("yyyy-MM-dd'T'HH:mm:ss.SSS")
.parse("2009-10-12T00:00:00.000);
cal.setTime(dataObject);
cal.getTimeInMillis();
According to the API, getTimeInMillis() returns "the current time as UTC milliseconds from the epoch."
EDIT: as _bravado pointed out, the Calendar API is currently not available for GWT (Issue 603). While this would get the appropriate time in a Java application, it isn't going to work here. There is information in the group about using GMT.
EDIT: Missing a closing bracket on the the Calendar.getInstance() call

Related

How do I tell Joda Time that the time I am giving it is for a specific time zone offset, even though the offset isn't given in the String?

I am working with an API that provides me with a ModifyDate field that is being given in CST (-06:00), but when passing the string in to Joda time and setting the time zone to America/Phoenix, Joda time thinks that the date/time I gave it is in UTC time zone because there is no offset information being given by the API (the time being returned is in CST, confirmed with the developers).
Side note: I am in Arizona where we do not recognize daylight savings time, so I can't just apply a static offset of -1 hour.
Here's an example of what I'm dealing with:
Field returned by the API:
"modifyDate": "2020-02-11T12:23:39.817Z"
Trying to format the date with Joda time:
DateTime time1 = new DateTime("2020-02-11T12:23:39.817Z", DateTimeZone.forID("CST6CDT"));
System.out.println(time1);
DateTime time2 = new DateTime(time1, DateTimeZone.forID("America/Phoenix"));
System.out.println(time2);
System.out.println("----------------------------");
DateTime time3 = DateTime.parse("2020-02-11T12:23:39.817Z");
System.out.println(time3);
System.out.println(time3.toInstant());
System.out.println(time3.withZone(DateTimeZone.forID("America/Phoenix")));
System.out.println(time3.toDateTimeISO());
System.out.println(time3.toDate());
System.out.println("--------------------------------");
Output:
2020-02-11T06:23:39.817-06:00
2020-02-11T05:23:39.817-07:00
----------------------------
2020-02-11T12:23:39.817Z
2020-02-11T12:23:39.817Z
2020-02-11T05:23:39.817-07:00
2020-02-11T12:23:39.817Z
Tue Feb 11 05:23:39 MST 2020
--------------------------------
As you can see in the first two outputs, by trying to apply the time zone for CST, the time provided is offset by -6 (to be expected if the time provided was in UTC). By setting the time zone to America/Phoenix, the offset is -7 (also to be expected). However, as I mentioned, the time that I am passing into DateTime is not UTC, it is CST.
How can I tell DateTime (or even some other library, for that matter) that the time being provided is in CST? Again, keeping in mind that when daylight savings time changes, the offset needs to be managed properly.
In this case, the time being provided by the API was incorrectly being provided as UTC, even though the time is CST, as pointed out by OleV.V. The cleanest solution to this problem was to use DateTime.withZoneRetainFields(), as mentioned by shmosel.
For whatever reason, however, if I created the DateTime object by using the constructor, I couldn't adjust the time zone with withZoneRetainFields(), instead, I had to use DateTime.parse().
I adjusted for the time zone being off by using the following logic:
DateTime time4 = DateTime.parse("2020-02-11T12:23:39.817Z").withZoneRetainFields(DateTimeZone.forID("CST6CDT"));
System.out.println(time4);
System.out.println(time4.withZone(DateTimeZone.forID("America/Phoenix")));
Output (correct)
2020-02-11T12:23:39.817-06:00
2020-02-11T11:23:39.817-07:00
Hopefully, this will help someone else if they come across the same problem.

How to get time from user with respect to timezone

Good day,
I am working on a project reporting.
and its my first time i have to deal with datetime.
I have database mongodb, as we know mongodb stores date time in UTC.
now i would like to show data from users provided date and time zone.
for example if i am login in my system i can set my timezone from dropdown. say i choose GMT+05:00 now if i choose date start and end as 2018-07-05 and 2018-07-06
how can i get the proper time with user specified time zone.
I guess if user has selected the time zone GMT+05:00 then date must be start from 2018-07-04 19:00:00 and 2018-07-05 19:00:00 minus 5 hours from given time.
how can i achieve this is java.
String userTimeZone = "Asia/Samarkand";
String userDate = "2018-07-05";
ZoneId zone = ZoneId.of(userTimeZone);
Instant dbInstant = LocalDate.parse(userDate)
.atStartOfDay(zone)
.toInstant();
System.out.println(dbInstant);
This prints what you had expected:
2018-07-04T19:00:00Z
I don’t know MongoDB’s JDBC driver, but I assume it would be happy to accept an Instant and store it in UTC in the database.
GMT+05:00 is not really a time zone, it’s a GMT offset. If your user is in a time zone that uses the same UTC offset always, it would work. But politicians tend to change their minds, so even if that time zone doesn’t use summer time (DST), it may do in a couple of years. And very many time zones already do. Therefore your user should pick a proper time zone like Asia/Tashkent, for example.
Edit: I understand from your comment that MongoDB expects a java.util.Date object. Funny and old-fashioned, but in that case the conversion is straightforward when you know how:
Date dbDate = Date.from(dbInstant);
System.out.println(dbDate);
On my computer in Europe/Copenhagen time zone this printed:
Wed Jul 04 21:00:00 CEST 2018
Don’t be fooled: this is the correct time. Date.toString (implicitly called through System.out.println) grabs my JVM’s time zone setting and uses it for generating the string. The Date itself doesn’t have a time zone in it and holds the same point in time as the Instant.
Link: Oracle tutorial: Date Time
If you already have the user selected time zone what you need to do is parse the date from DB to GMT:
Date dateFromDb = getDateFromDb(); // date from db
LocalDateTime localDateTime = LocalDateTime.ofInstant(new Date().toInstant(), ZoneId.of("GMT")); // parsing date to GMT but using LocalDateTime
Date correctDate = Date.from(localDateTime); // transforming into java.util.Date

How to handle CST to CDT or vice versa using XMLGregorianCalendar

I had the below issue During daylight change CST-CDT reset.
Am getting the Input from Was8.5 server 2018-03-11-05.00 (UTC-5) as expected, but when it comes to WAS7 server, the below method returns Sun Mar 10 00.00.00 CST 2018 instead of Sun Mar 11 00.00.00 CDT 2018
/*
* Converts XMLGregorianCalendar to java.util.Date
*/
public static Date toDate(XMLGregorianCalendar calendar){
if(calendar == null) {
return null;
}
return calendar.toGregorianCalendar().getTime();
}
I know the server date/timezone reset didn’t take place properly, but in case if I want to get right Time when CST to CDT change or vise versa. How can I rewrite the code to convert XMLGregorianCalendar to java.util.Date in Java?
Something like,
If incoming request was CST(UTC-6), the toDate(XMLGregorianCalendar calendar) returns CDT (UTC-5). then I want toDate() should return CST (UTC-6).
the same way,
If incoming request was CDT(UTC-5), the toDate(XMLGregorianCalendar calendar) returns CST(UTC-6). then i want toDate() should return CDT(UTC-5).
java.util.Date doesn't have a timezone. It just have a long value that represents the number of milliseconds since unix epoch.
What you see (Sun Mar 10 00.00.00 CST 2018) is the result of toString() method, and it uses the JVM default timezone to convert the long value to a date and time in that timezone. See this article for more details:
https://codeblog.jonskeet.uk/2017/04/23/all-about-java-util-date/
Anyway, one way to really know what's happening is to check this long value:
long millis = calendar.toGregorianCalendar().getTimeInMillis();
And then you can print this value in UTC:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss XXX");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(sdf.format(new Date(millis)));
Or, if you use Java 8:
System.out.println(Instant.ofEpochMilli(millis));
This will tell you the UTC instant that the Date corresponds to, so you can debug your code a little better than relying on Date::toString() method, which is confusing and misleading.
Regarding your main issue, I've tried to reproduce (I'm using Java 8 because it's easier to manipulate than using Date). First I created a date/time corresponding to 2018-03-11 in UTC-05:00, and I assumed the time to be midnight:
// March 11th 2018, midnight, UTC-05:00
OffsetDateTime odt = OffsetDateTime.parse("2018-03-11T00:00-05:00");
Then I converted this to America/Chicago timezone, which is a zone that uses CST/CDT:
// get the same instant in Central Time
ZonedDateTime zdt = odt.atZoneSameInstant(ZoneId.of("America/Chicago"));
Then I printed this:
// print the date/time with timezone abbreviation
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm xxx z", Locale.US);
System.out.println(zdt.format(fmt)); // 2018-03-10 23:00 -06:00 CST
Note that the result is 2018-03-10 23:00 -06:00 CST: March 10th in UTC-06:00.
That's because in 2018, Daylight Saving Time starts only at 2 AM of March 11th. At midnight, DST has not started yet, so the offset is still UTC-06:00.
Anyway, your conversion code is correct, because Date just represents a point in time (a count of elapsed time since epoch) and doesn't have timezone attached to it. Perhaps the problem lies somewhere, and checking the millis value might help you to understand what's going on (my guess is that XmlGregorianCalendar sets the time to midnight when it's not present, which would explain the result of Sun Mar 10 00.00.00 CST 2018).
If that helps, the exact UTC instant where DST transition occurs (March 11th 2018 at 2 AM in UTC-06:00) corresponds to the millis value 1520755200000. If your dates in March 2018 have a value lower than that, it means they're before DST starts, and they'll be in CST.
My first suggestion is that you don’t need what you are asking for. As I see it, you’ve got a date and a UTC offset, and I don’t really see that the offset adds any useful information. Just take the date. I believe what has happened was that a point in time after the transition to summer time on March 11 was stripped of the time-of-day, but the UTC offset was kept for whatever reason or maybe for no reason at all. When giving the time at start of day (00:00), the offset disagrees with your time zone of America/Chicago (or Central Time Zone, but the ID in region/city format is unambiguous and recommended).
And don’t use java.util.Date for your date. That class is long outdated. Today we have so much better in java.time, the modern Java date and time API. Furthermore its LocalDate class is better suited for a date without time-of-day because this is exactly what it is, while a Date is really a point a in time, that is, a whole different story. Depending on taste conversion from XMLGregorianCalendar can happen in two ways.
The direct way
return LocalDate.of(calendar.getYear(), calendar.getMonth(), calendar.getDay());
With your XMLGregorianCalendar of 2018-03-11-05:00 the result is a LocalDate of 2018-03-11.
The indirect way via GregorianCalendar and ZonedDateTime:
return calendar.toGregorianCalendar().toZonedDateTime().toLocalDate();
The result is the same. The advantage of the latter is you don’t need to concern yourself with the individual fields of year, month and day-of-month. Among other things this means you don’t risk putting them in the wrong order.
If you do insist on keeping the time zone or UTC offset, at least take the offset. Sun Mar 11 00.00.00 CDT 2018 doesn’t make sense because March 11 at 00:00 hours DST was not yet in effect (it began at 02:00). Such a non-existing time will just confuse everyone. Convert your calendar object to OffsetDateTime:
return calendar.toGregorianCalendar().toZonedDateTime().toOffsetDateTime();
Result: 2018-03-11T00:00-05:00. This point in time exists.:-)
Since your calendar comes from a foreign system, you will probably want to validate it since any field may be undefined and return DatatypeConstants.FIELD_UNDEFINED. When using LocalDate.of(), you may decide that its argument validation is enough since it will object to DatatypeConstants.FIELD_UNDEFINED being passed as an argument. toGregorianCalendar() on the other hand will tacitly use default values, so when using it I would consider validation indispensable.
What went wrong in your code?
I ran your code, and similarly to iolus (see the other answer) I got Sat Mar 10 23:00:00 CST 2018. This the correct point in time. As iolus also explained, this is Date.toString rendering the point in time this way. The Date object itself doesn’t have a time zone or UTC offset in it. So I should say that your code was correct. It was just you getting confused by the toString method. Many have been before you, and the good solution is to avoid the Date class completely. Also I would think that your observations have nothing to do with any difference between WAS 7 and WAS 8.5.

How to keep original timezone with JodaTime

I have date in String format I need to parse. The format is as following with timezone from all over the world :
String stringDate = "2016-04-29 12:16:49.222+04:30";
String pattern = "yyyy-MM-dd HH:mm:ss.SSSZ";
It seems that java.util.Date doesn't accept timezone with : separator. So I'm trying with Jodatime library :
DateTime formattedDate = DateTimeFormat.forPattern(pattern).parseDateTime(stringDate);
LocalDateTime formattedDate2 = DateTimeFormat.forPattern(pattern).parseLocalDateTime(stringDate);
MutableDateTime formattedDate3 = DateTimeFormat.forPattern(pattern).parseMutableDateTime(stringDate);
System.out.println(formattedDate);
System.out.println(formattedDate2);
System.out.println(formattedDate3);
These lines output :
2016-04-29T09:46:49.222+02:00
2016-04-29T12:16:49.222
2016-04-29T09:46:49.222+02:00
As far as I understand the formatter modify output timezone to comply on mine (I'm in Paris, UTC+2), but I want the output keep its original timezone. Is it possible to do it with Jodatime library? Or should I change for another?
Edit :
Actually I need to get a Date object on which the timezone offset would be 270 (the timezone offset of the stringDate : 4 hour and 30 minutes) in place of 120 (my local timezone offset):
System.out.println(formattedDate.toDate().getTimezoneOffset()); // I expect 270 but I get 120
What you missed is DateTimeFormatter#withOffsetParsed:
Returns a new formatter that will create a datetime with a time zone equal to that of the offset of the parsed string.
Otherwise the formatter will parse it into your local time zone (surprising, I know).
#Test
public void preserveTimeZone() {
String stringDate = "2016-04-29 12:16:49.222+04:30";
String pattern = "yyyy-MM-dd HH:mm:ss.SSSZ";
DateTime dt = DateTimeFormat.forPattern(pattern).withOffsetParsed().parseDateTime(stringDate);
System.out.println(dt); // prints "2016-04-29T12:16:49.222+04:30"
}
As for your edit - java.util.Date does not hold time zone information and the deprecated getTimezoneOffset() method only
Returns the offset, measured in minutes, for the local time zone relative to UTC that is appropriate for the time represented by this Date object.
So you'd better use Joda Time or java.time classes to handle time zones properly.
When I run the same code that you have posted, I end up with
2016-04-29T02:46:49.222-05:00
2016-04-29T12:16:49.222
2016-04-29T02:46:49.222-05:00
which if you will notice, has different hour values AND time-zone values. However, if you look at their millis:
System.out.println(formattedDate.getMillis());
System.out.println(formattedDate2.toDateTime().getMillis());
System.out.println(formattedDate3.getMillis());
you'll see the output
1461916009222
1461950209222
1461916009222
So they have the same epoch time, but are printed out differently. This is due to the mechanism of toString() on DateTime objects, and how they are to be interpreted.
DateTime and LocalDateTime(MutableDateTime is just a mutable version of DateTime) deal with the same epoch time in different ways. LocalDateTime will always assume that epoch time is UTC time(per the javadoc for LocalDateTime), while DateTime will assume that epoch is represented in the time zone of the Chronology which it holds(per the javadoc again). If the TimeZone is not specified at construction time, then the Chronology will assume that you want the timezone of your default Locale, which is set by the JVM. In your case, the default Locale is Paris France, while mine is St. Louis USA. Paris currently holds a +2:00 time zone offset, while St. Louis has -5:00, leading to the different time zone representations when we print it.
To get even more annoying, those offsets can change over time. If I come back in 6 months and try to answer this again, my values will show -6:00 (stupid Daylight savings time!)
The important thing to remember is that these two dates have the same epoch time: we are talking about the same instant in time, we are just representing that time differently when we print it out.
If you want to use a different time zone for representing the output of the parse result, then you can set the DateTimeZone during formatting using DateTimeFormat.withZone() or DateTimeFormat.withLocale:
DateTimeFormatter sdf = DateTimeFormat.forPattern(pattern).withZone(DateTimeZone.forOffsetHoursMinutes(4,30));
System.out.println(formattedDate.getMillis());
System.out.println(formattedDate2.toDateTime().getMillis());
System.out.println(formattedDate3.getMillis());
which will print
2016-04-29 12:16:49.222+0430
2016-04-29 12:16:49.222
2016-04-29 12:16:49.222+0430
notice that the LocalDateTime version still prints out without the TimeZone. That's kind of the feature of LocalDateTime: it is represented without having to deal with all this business.
So that is why your printing values look weird. To further your question about getting a java.util.Date object from the parsed DateTime object: toDate will give you a java.util.Date which represents the same epoch time. However, java.util.Date behaves similarly to DateTime, in that unless otherwise stated, it will use the TimeZone of the default Locale. If you know the Locale ahead of time, then you can use the toDate(Locale) method to ensure you use that Locale's TimeZone offset.
It gets a lot harder if you don't know the TimeZone ahead of time; in the past, I've had to hand-parse the TimeZone hour and minute offsets to determine the proper TimeZone to use. In this exact case that's not too difficult, since the last 6 characters are extremely well-formed and regular(unless, of course, they aren't :)).

Java Date toString contains a timezone... Why?

I wrote some code today in VB6 which would get me the number of milliseconds since 1/1/1970, so I could then send the value off to a java application which would parse that value like new Date(Long.parse(milliseconds)). I understand that the milliseconds the Date(Long) is looking for is the number of milliseconds since epoch in GMT. The machine I am running on is on CDT here in the US. When I get the toString value of the date parsed from the milliseconds, this is the value I get:
Tue Aug 11 15:40:50 CDT 2015
Is the CDT just there because the local machines timezone is CDT? I just think its a little weird that the constructor for Date would assume that a date derived from the milliseconds since epoch in GMT would implicitly be in the local machines timezone, rather than being offset (in this case) by -5 hours.
Is the CDT just there because the local machines timezone is CDT?
The timezone for display purposes is based on the default time zone.
The millis in the Date is relative to epoch and it doesn't have a time zone of its own.
It is taken since 00:00 1/1/1970 GMT or if you prefer 17:00 12/31/1969 CDT.
would implicitly be in the local machines timezone
The use of the local time zone is for display purposes only. Use another time zone or serialize the Date and send it to a machine in another timezone and it will use the local timezone again.
You're correct it's showing CDT in the toString() because your locale indicates that is the correct timezone for you. The Date object itself doesn't care about timezones and is a glorified wrapper around the Unix epoch in milliseconds. Generally you should use toString() for debugging purposes, and use a date formatter to actually display dates to the user (optionally specifying an explicit timezone instead of the one specified by the user's locale).
The Javadoc for Date.toString() only specifies the format of the string, it doesn't actually say anything about which timezone is used. I wouldn't rely on toString() always returning the default Locale in every implementation of Java.
You can use a custom representation of a date by using the correct format
Read this post, it might help you
Change date format in a Java string
The number of milliseconds since epoch began is NOT in the timezone known as UTC. It is not in any time zone. The epoch value is the same in ALL time zones. That epoch millisecond value is the same in London as it is in New York or San Francisco for that instant in time.
The Date function always uses the current default time zone if you don't set one. So for you, yes, the local machines timezone is CDT. Again, the epoch value in CDT is exactly the same as everywhere else on the planet, so there is no real reason to pick UTC when your machine thinks it is in central time.

Categories