How to get client/request timezone in jsp?
Unfortunately this information is not passed in HTTP headers.
Usually you need cooperating JavaScript to fetch it for you.
Web is full of examples, here is one http://www.coderanch.com/t/486127/JSP/java/Query-timezone
you cannot get timezone, but you can get current time from client side.i.e. through javascript and than post back. On server side, you can convert that time to GMT/UTC. The UTC shows the TimeZone.
If you just need the local timezone in order to display local times to the user, I recommend representing all times in your service in UTC and rendering them in browsers as local times using Moment.js.
My general rule is to handle and store times in UTC everywhere except at the interface with the user, where you convert to/from local time. The advantage of UTC is that you never have to worry about daylight-saving adjustments.
Note that if you want to show the age of something (e.g. "posted 3 hours ago") you just need to compare the UTC timestamp with the current UTC time; no need to convert to local times at all.
Best solution for me is sending date/time as a string, and then parse with server's timezone to get a timestamp. Timestamps are always UTC (or supposed to be) so you will not need client's TimeZone.
For example, sending "10/07/2018 12:45" can be parsed like:
SimpleDateFormat oD = new SimpleDateFormat();
oD.applyPattern("dd/MM/yyyy HH:mm");
oD.setTimeZone(TimeZone.getDefault()); // ;)
Date oDate = oD.parse(request.getParameter("time"));
Obviously you can set your specific date/time format.
Related
My project uses Javascript and Java (Android) for the client and Java for the backend.
When I started working on my project, I stored dates as days from epoch (long) and all was good. I then found out that my project doesn't work well with timezones. Suddenly dates were +1 -1 days off. Depending on the client's location in the world.
After a short investigation, I saw that the foolproof way to avoid it was to store the dates as String yyyy-MM-ddT00:00 so when using the Javascript's new Date(dateStr), it creates it correctly and all was good. Ofcourse I could store the dates as yyyy-MM-dd and just send it to the client as yyyy-MM-ddT00:00 but that won't solve the question I have.
After that, I was wondering whether Java (backend) is handled correctly. I use LocalDate when I want to "play" with dates and LocalDate.parse doesn't like yyyy-MM-ddT00:00 format, instead it works with yyyy-MM-dd so whenever I needed dates, I did LocalDate.parse(dateStr.substring(0,10)). LocalDateTime does work with yyyy-MM-ddT00:00 but I don't need the time part and it had its own issues, which I don't remember what they were at the moment.
So now I have a lot of String manipulation (inside loops) that actually creates more String objects. One can say it's not that much of a stress and I shouldn't pay attention to that but I want to make sure I'm not missing something and maybe there's another way (maybe silly enough that I've missed) to overcome this.
Thanks
Update: The events are stored from a different source and only the date itself is important so if an event happened on 2020-06-17, this is the date all users should see, no matter where they are.
I'm using new Date(dateStr) in Javascript. If dateStr is 2020-06-17, the date object uses the client's timezone and the date might be +-1 depending on the client's timezone. If dateStr is 2020-06-17T00:00 then the date object is created as expected no matter where the client is located.
Assuming the above, which I hope is clearer now, creating String objects over and over again is a memory stress that I should consider or is it something Java handles with no problem and I shouldn't worry about this?
My question was closed and I was told to edit it to be more focused. After editing my question, how can I re-open my question to answers?
As you have discovered, storing dates in terms of days since some epoch only works if everyone who uses your system is using the same time zone. If two different users in different time zones have a different idea about the date on which some event occurred (e.g., the person in New York says that the system crashed on Sunday night, but the the person in Hong Kong says it crashed on Monday morning), then you have to store the time zone in which the event occurred in order to show the date of that event accurately.
But if that's the situation you're in, why not just store the time zone along with the date? There's no compelling reason to combine the date and timezone into a string.
When you parse a ISO-formatted timestamp into a LocalDate using only the first 10 characters, be aware that you're losing the time zone information. Implicitly the LocalDate that you get is in the time zone of the original timestamp. So if the original timestamp is New York time, and you take the date part and add 1 day, then you'll get the next day in the New York time zone. But if you then take the date from a second timestamp, you can't compare it to the date you got from the first timestamp, in terms of determining if it represents the "same day." You can only test for "same day" if both dates are implicitly in the same time zone.
UPDATE
After reading your additional comments, I realize that what's happening is this. You have a date stored in your database, like 2020-06-15. You send that to the UI as the string '2020-06-15' and then do new Date('2020-06-15') and then you're surprised when you render the date in the UI and get June 14!
This is the transformation that happens:
The string '2016-06-15' gets parsed into a JavaScript Date representing midnight UTC on the June 15.
When you render the date, it gets converted into a string using the browser's local time zone, which (if you're in the United States) will give you June 14, because at midnight UTC on June 15 it's still June 14 in all time zones west of Greenwich.
You discovered that if you make the string "2020-06-15T00:00" that it works, because now JavaScript uses the browser's local time zone to parse the string. In other words, this string means midnight local time, not UTC, on June 15. So now the sequence is:
'2020-06-15T00:00' gets parsed using the local time zone and becomes June 15 4:00AM UTC.
When you render the date, it gets converted back to local time and is rendered as June 15.
The easiest way to avoid all this messiness is just to send the regular date string '2020-06-15' to the UI and render it using DateTimeFormat, specifying the time zone as UTC:
new Intl.DateTimeFormat('en-US', {timeZone: 'UTC'}).format(d)
Since dates in JavaScript are always UTC, and you're asking DateTimeFormat to output the date in UTC, no date shift occurs.
You could also use the Date methods getUTCFullYear, getUTCMonth, etc. to get the date components and format them however you like.
Once you're no longer sending dates back and forth with "T00:00" appended, you can just use LocalDate on the Java side.
Don't spend even a second worrying about the time required to manipulate strings. Think about the incredible amount of string manipulation that is necessary to build even a simple web page. A few more strings here and there isn't going to make a difference.
There is rest-controller in spring applcation
#GetMapping
public String findByParams(#RequestParam("date") #DateTimeFormat(pattern = DATETIME_FORMAT) ZonedDateTime date) {...}
So, ZonedDateTime does't save my +03:00, +04:00 offsets and shift all times to Z
How to customize it to save my offset in repsonse?
for example, I saved date like this
2020-05-07T17:10:45.001+03:00
but #DateTimeFormat parsed it like
2020-05-07T14:10:45.001Z
But I need in +03:00 offset with time, how to fix it.
The issue is save not only for request params, but for dto fields too..
for example, I saved date like this
2020-05-07T17:10:45.001+03:00
but #DateTimeFormat parsed it like
2020-05-07T14:10:45.001Z
And that is perfectly valid as it describes THE SAME INSTANT but represented in different timezones. Having this you are able to present the exact same instant of time to users in different timezones in their relative (local) time while having consistent timeline of events (eg in the datebase). I would leave it as is because most of integration with your API will work out of the box. 2020-05-07T14:10:45.001Z is equal to 2020-05-07T14:10:45.001+00:00 but it is a matter of convinience to have it shorter way :)
so as to
How to remember offset when save json-dto using #DateTimeFormat?
You don't. You are free to output data in any timezone (including the one required)
Here is how to do "hardcoded version'
https://stackoverflow.com/a/46653797/1527544
I have a Java service which needs to return date/time information that is formatted relative to a user's current timezone (C#). For example, say a user is on the west coast (pacific time) where it is 8:00pm. They connect to a service that is hosted in the midwest (central time) where it is 10:00pm. If the user were to ask the server for the current time, the server should respond, "8:00pm" for the user.
My thought is that the client application (C#) will pass information to the service about its current timezone or UTC offset. Java will then create/format all dates using that timezone.
However, I am having trouble finding a good way to pass C# System.TimeZone information in a way where Java can create and use a java.util.TimeZone object. I can get the UTC offset from C# but not a three digit timezone code. In Java I can create a TimeZone from a three digit code but can't find a way to create one from a UTC offset. From everything I've seen in Java, TimeZones are created with a code ("PST") or country/region ("America/Los_Angeles"), and I don't believe there is a clear way to get the timezone in this format in C#.
How might this be accomplished?
Work In UTC
As the comment suggested, usually the best way to go is to work your business logic in UTC. Adjust into a local time zone only for presentation when expected by a user.
So your Java backend should be returning a UTC date-time value. Usually the best way to do that is to serialize the date-time value as a string in the standard ISO 8601 format. Then let the client app handle the presentation by generating a string representation of the date-time value adjusted into a particular time zone.
See this Question about best practices for date-time work.
But somehow this is not feasible in the context of this Question. So the client app needs to communicate to the backend the desired/expected time zone.
Time Zone
Avoid the 3-4 letter codes such as EST or IST. These codes are neither standardized nor unique. Furthermore they invoke Daylight Saving Time in a confusing way.
Instead use official time zone names. These are mostly in the format of "continent", slash, and "region/city" in English, such as America/Montreal or Asia/Kolkata.
.Net Fails To Support Proper Time Zone Naming
Unfortunately, it looks like the .Net team did not know about proper time zone naming.
The System.TimeZone class offers properties such a StandardName. But the examples in the System.TimeZone doc show "Pacific Standard Time" rather than a proper name such as "America/Los_Angeles".
Noda Time
My first suggestion is to consider using the Noda Time project, an alternative date and time API for .NET. It was inspired by the highly successful Joda-Time library in Java, which in turn inspired the new java.time framework built into Java 8 and later.
Looks like Noda Time has support for proper time zones. Rather than use System.TimeZone, use Noda Time to obtain the time zone information.
Roll Your Own Mapping
If Noda Time is not an option, then I might look to see if my users are all in a few time zones. If so, I would make my own mapping of such as "Pacific Daylight Time" returned by C# the standard name for a time zone being the proper name "America/Los_Angeles".
While writing integration test I was expecting a hardcoded date in the response.
Basically I hardcoded expected date value '2020-11-10T00:00:00.000-05:00'
and ran new GregorianCalendar(2020, 10, 10).getTime()
When I put and assert and run it locally it passes, however when the same code was pushed to bamboo build server the actualValue it generated was'2020-11-10T00:00:00.000Z' and so my test failed.
Why the same calendar.getTime generating two different times, is it because the server machine is configured to be on GMT?
Can I do something to have them the same time or any other workaround?
NOTE: Making it string or comparing dates without time is not an option here, as I am using Spring MockWebServiceServer, where in I must hardcode the responseXML and specify date, something like this in Enum.
REQUESTAUTOMATESETTLEMENTWORKCASE("<aut:AutomateSettlementWorkcaseRequest xmlns:aut=\"http://www.abcd.com/abcd/workflow/services/workcase/model/AutomateSettlementWorkcase_1_0_0\">" +
" <aut:customerAccountId>5049903033584324</aut:customerAccountId>\n" +
" <aut:settlementDate>2020-11-10T00:00:00.000-05:00</aut:settlementDate>\n" +
" </aut:AutomateSettlementWorkcaseRequest>"),
The "-5" part in your input data is throwing it off... ideally you should specify the time zone when constructing the calendar, and then set it to 5am UTC (for example). Basically, 2020-11-10T00:00:00.000-05:00 is the same instant as 2020-11-10T05:00:00.000Z.
Now, what we don't know is whether it's important to you that you preserve the offset from UTC. If it is, you need to set an appropriate time zone in the calendar - one which has the same rules as whatever's generating your input data. If it isn't, I'd use UTC and set the time appropriately.
I would personally recommend using Joda Time instead of Calendar and Date though - it's a much better date and time API. No 0-based months, for starters :)
My apologies for the extremely basic question, I think I know the answer but would like to verify:
When refering to time zones and how they are usually stored in a database and in a java.util.Date:
When saving a date field in a database, it is timezone agnostic (e.g. always saves in UTC)
When using a Java Date object the date it is also timezone agnostic
Time zone is depeneded only when formatting and parsing dates (DB and Java)
If using Java - it will use the JVM user.timezone to format / parse dates
If using Java on Windows - Java will take this from the Regional settings automatically
The database timezone (and it's machine's timezone) is irrelevant to the Java JDBC client
The timezone of the Database Server is relevant only for direct SQL parsing and formating
My questions are:
Are all of the above assumptions correct? some are? all incorect?
Is there a reference / official source that verifies this more "officially"?
The assumption are mostly correct for Java. They are not necessarily correct for databases, as there are variations.
Java handles time zones with Calendar objects. The java.util.Date object always contains the UTC value.
Databases generally store and return dates and timestamps (with hour, minutes, etc.) as they are written, regardless of the internal format used by storage. If you store 2010-12-25, you will retrieve the same value regardless of the time zone of the clients or server.
Some databases have the TIMESTAMP WITH TIMEZONE data type which stores both the timestamp and the time zone separately.
Dates and timestamps are converted between Java and Database, usually in a manner that the subclasses of java.util.Date that are used are interpreted in the JDBC client's time zone.