I wrote a webapp using spring+hibernate. I developed everything on windows and then I moved it to a Linux virtual server (Aruba, an Italian provider). I noticed an annoying thing: when dates where saved on windows the time would be the same of my "wall clock", so if I read 13:45 I will have the same hour in the mysql row. This doesn't happen on Linux anyway. In fact the linux machine is on CEST as well (my timezone), I got it typing "date" in the shell. But I get the dates saved in the DB with an offset that is relative to GMT. Again, my app always displays everything in GMT (Including GMT as a time zone if I choose to format the dates to display the time zone) and mysql saves everything in that format. How do I control all this?
I post the solution by myself, because I think it's worth having it in this site.
First of all: mySql doesn't store any timezone information. So say that you are running on GMT+4 and you write a couple of records that contain date fields. Then you move your system in GMT-2 you read those records (perhaps importing the data from mysqldump). If your system and VM have GMT-2 as timezone the dates you read will be taken as if they were written in GMT-2 and NOT ADJUSTED.
Solution: Take control of your VM timezone by using -Duser.timezone="GMT" command line option (you can even put this in your Tomcat startup script) or your preferred timezone (but GMT is better, let me explain why). This way you'll know for sure which timezone your VM is running. This doesn't mean that Java VM will assume that your system time is the one you specified in your user.timezone, it will know the system timezone and adjust dates accordingly. In fact if you are not in GMT, you will see dates in adjusted to GMT and saved to DB accordingly. This way you'll be sure that you are using that as a reference.
The problem is that if you take a date object and you do myDateObject.toString(), you'll get the date adjusted to GMT, with the hour offset. Which is not what you'll probably want.
The solution is to use SimpleDateFormat and do somthing like this when you have to output a date:
SimpleDateFormat dateFormat = new SimpleDateFormat(
"HH:mm dd/MM/yyyy z", Locale.ITALY);
dateFormat.setTimeZone(TimeZone.getTimeZone("Europe/Rome"));
Everything will get converted the right way. You can even go further if you are developing a web app. You can extract the timezone from the HttpRequest and adjust date output accordingly, but I didn't go so far as I'm writing an application that is intended for Italian users only :D (yay).
Hope this will help.
Related
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.
Given a timezone like 'EDT' in java, is there a way to set an arbitrary datetime in java to be in that timezone and print with the correct label, (either EDT or EST)?
Some context:
I am developing a weekly report generation feature that needs to timestamp reports in the timezone of the user who first configured the report. I would like to label the reports using the 3 letter timezone labels like 'EST' or 'CST,' so that users would see a message like "This report was generated at 03-28-2018 12:00:00 pm EDT." (I realize these can be ambiguous.)
Reports are generated as pdfs on the server so all information must come from the report configuration saved in the database.
Right now when the client posts a new report configuration, it includes the three letter timezone in the configuration along with its offset (eg 'GMT-0400' for EDT), and use that to create a LocalDateTime with the saved offset, then print it with saved label. Obviously this won't account for daylight savings, so I need a better solution.
For reference I am using AngularJS on the client.
It turns out my problem needed a client side solution, based on comments and this question, I used moment.js moment.tz.guess(); to get an IANA timezone which is included when configuring a new report.
Once the server knows the IANA timezone creating the zoned datetime is simple:
String timezone = "America/New_York";
ZonedDateTime timestamp = ZonedDateTime.now().withZoneSameInstant(ZoneId.of(timezone));
I have tried the following so I can get Date based on my timezone which is "Africa/Johannesburg" or GMT+2:00 but Google servers always return time using its own timezone which is 2 hours behind mine.
I have done the FF:
in appengine-web.xml I have set
<property name="user.timezone" value="Africa/Johannesburg"/>
I have also tried TimeZone.setDefault(TimeZone.getTimeZone("GMT+2:00")); before creating Date object
in the init method of my servlet, I have also tried
#Override
public void init() throws ServletException {
TimeZone.setDefault(TimeZone.getTimeZone("GMT+2:00"));
}
But this thing won't just work. Because JDK date is not thread safe, I am using JodaTime, which works well, In fact when I do new DateTime(DateTimeZone.forID("Africa/Johannesburg")) I get correct time but for legacy issues, I have to store date in JDK date hence have to convert Joda to JDK Date by invoking .Date(), then the time is completely screwed up in wrong timezone.
Does anyone by chance know how to set this without having to subtract the hours difference.
You can't. The system timezone is not changeable. You should store all of your dates in unix time and convert them to a Date or Calendar object using your timezone. I also would not assume that GAE is always going to use the same timezone...
When you save any date in Datastore it will be saved in the timeZone you have set in your JVM, thats why before starting the app I always set it to UTC:
//To avoid difference of dates depending on where the server is located
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
Nonetheless when you browse the datastore in the gcloud console it will be shown in your local timezone (probably it gets the browser timezone and adapts the response to you). But when you query it back the calendar date taken in count will be the one you used for saving it (In my case UTC).
I have a webapp that is to be deployed on server having Pacific TimeZone setting. My app is capable of handling PST<->PDT date conversions in calculations but i am facing issue handling missing hour/Invalid Time as described below.
Invalid Time – Between 02:00 AM to 03:00 AM on second Sunday in March due to forward auto-adjustment of clock, this time does not exist in Pacific Time Zone.
So whenever date like 10-Mar-2013 02:00:00 is entered system automatically converts it into 10-Mar-2013 03:00:00. I understood this is happening because this time is actually does not exist in Pacific timezone.
But as per requirement server timezone can not be changed (for eg. GMT) and still need to capture above time (10-Mar-2013 02:00:00). Additionally server auto-adjutment clock settings also can not be changed so i have to do application code change to support above.
Thanks in advance for your help.
Adding code for more clarification:
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyy HH:mm:ss");
//sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = sdf.parse("100313 02:00:00");
Date date1 = sdf.parse("100313 03:00:00");
System.out.println(sdf.format(date));
System.out.println(sdf.format(date1));
Output:
100313 03:00:00
100313 03:00:00
If i uncomment commented line then output:
100313 02:00:00
100313 03:00:00
Regardless of the time zone setting of the computer, you should always be able to get the current UTC time. Java abstracts this from the OS details, so any time the documentation says you are getting a UTC value (such as milliseconds from 1/1/1970 UTC) then it is accurate. There is no such thing as missing or ambiguous time in UTC.
The reason that it is recommended your servers are set to UTC time zone has to do with the way the system bios clock is synchronized with the operating system's clock. Microsoft Windows operating systems keep the bios on local time and adjust it as necessary, while Linux and Macintosh keep the bios permanently on UTC. Because of this, on Windows systems, there is a remote possibility that the clock is read incorrectly if the adjustment didn't work for some reason. More on this issue here.
If your application is converting dates entered to values that only make sense in the computer's local time zone, then you have projected that time zone on to your users. For desktop applications, this is probably correct because the user is running the code on their own computer. For web applications (and other server-side code), this is certainly the wrong thing to do, because it is possible for the client to be in a different time zone than the server.
Please update your question to show the specific code from your application that is causing the problem you described. We can then point you at the specific changes you need to make so your application behaves correctly.
My server is in US and I am accessing the application in India through
web browser, in that case what TimeZone.getDefault() will return?
If it returns Time Zone based on India on basis of what it will return?
I have changed in control panel setting to different locale and
different time zone of the system even though it is not changing based
on my settings.
I have written the code as fallows...
def dateFormat = DateFormat.getDateTimeInstance(DateFormat.DEFAULT,DateFormat.DEFAULT,Locale.getDefault())
dateFormat.setTimeZone(TimeZone.getDefault())
It's going to return the timezone of the JVM TimeZone.getDefault() is executed on. So if the application is running on a server in India, it will be something like "Asia/Calcutta".
Default time zone is usually set for host, not user or application. In your case it will be default time zone for a server where your application is running, most probably US time zone.
Try to run command date +%Z in Unix console on server.
This is a matter of 'where this code executes'. If you are talking about a web application which is being accessed by a browser in India, the kind of date you get will be in US. Well, unless you set the proper locale and timezone for the user's session. In frameworks like Vaadin once you call setLocale() on the application it sets the timezone as well, but in other platforms you might have to explicitly use a date formatter with a specific timezone.