I stumbled upon this piece of code to get current time in EST with daylight saving. It seems to work fine, when checked on the internet by the time displayed in sites providing current time in EST with daylight saving.
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss.SSS");
dateFormat.setTimeZone(TimeZone.getTimeZone("EST5EDT"));
System.out.println(dateFormat.format(new Date()));
I just want to confirm, has anybody used something like this before or there is a better way to achieve the same. I cannot use Joda library due to constraints.
Thanks in advance.
Yes, that's the best (and indeed the only) way to do this using Java's standard libraries.
Related
I am looking for the most simple and cleanest way to fix the timezone for all dates in an Android app. The idea is to have the app running as if the user were in another timezone. Let me clarify what I am looking for:
Let's say the user's phone is set to America/New_York then I would like my app to show all dates (are in UTC) in the Europe/Amsterdam timezone, regardless of the timezone that is set on the phone itself. And if I make a comparison with a new Date() it would be very nice if that new Date() is also in the current time of the Europe/Amsterdam timezone.
After searching the internet for solutions, I started to get the feeling that I will have to update every place in my app where a Date is used and force the use of the target timezone, like the solution of this stackoverflow post: Converting UTC dates to other timezones
Does anybody know how to get this done in a more easy and cleaner way?
The answer for anyone using java.time, the modern Java date and time API.
java.time does not include an option for setting the JVM default time zone. And wisely so. It’s not something you should want to do. By doing it you affect every program running in the same JVM, and also every part of your program and other program in the JVM may set it differently, ruining your intentions.
Avoid the need
In your time operations be explicit about which time zone you want, and you will always know what you get independently of the JVM setting. Example:
System.out.println(ZonedDateTime.now(ZoneId.of("Asia/Dushanbe")));
Example output:
2021-05-09T00:36:25.171213+05:00[Asia/Dushanbe]
System.setProperty
If you have already written a lot of code relying on the default time zone of the JVM, the hack to set it is:
System.setProperty("user.timezone", "Australia/Tasmania");
System.out.println(ZonedDateTime.now());
This just printed:
2021-05-09T05:38:03.568350+10:00[Australia/Tasmania]
It’s not very robust, though, for the reasons mentioned in the beginning.
If you want validation of the string you are passing, use:
System.setProperty("user.timezone", ZoneId.of("Australia/Tasmania").getId());
Disclaimer
It seems from your question that you are already using the old, poorly designed and long outdated java.util.Date class and friends. I still wanted to post the answer for users who have the option to go modern. (You may also use each of the two ideas presented with the out-dated API.)
I would try TimeZone.setDefault(TimeZone) like in:
TimeZone.setDefault(TimeZone.getTimeZone("Europe/Amsterdam"));
(advice to check returned time zone, getTimeZone does not throw exception for unknown time zone - or use ZoneId instead of the String)
see TimeZone (this also mentions the user.timezone system property)
but I am not an android programmer/user
I have a TextClock in android that is supposed to be displaying the time from the system in 12-hour format only. The problem is it is displaying it in 24-hour format even when the system itself is displaying it in 12-hour format.
I have already used the android:format12Hour="HH:mm:ss" in my text view, but it seems to be completely ignoring this.
And I know android guidelines say to not overrride user's system setting, but this textclock is for an app that is specifically designed for mathematical calculations in oil drilling industry that need it displayed in 12-hour format.
Joop Eggen's solution worked.
In java SimpleDateFormat HH = 24h, hh = 12h
Not sure how I overlooked that. :) Thank you!
I just had this problem, solved it like this:
if (sharedPreferencesSingleton.getUserPreferences24HourMoodBoolean()){
textClock.setFormat12Hour("HH:mm");
textClock.setFormat24Hour("HH:mm");
} else {
textClock.setFormat24Hour("hh:mm a");
textClock.setFormat12Hour("hh:mm a");
}
This overides the format no matter what the default user setting is.
android:format12Hour specifies format to be used when TextClock is using 12hrs mode but it does not enforce it:
Specifies the formatting pattern used to show the time and/or date in 12-hour mode.
so if user's device is using 12hrs clock mode, then that format will be used, otherwise android:format24Hour is used.
in oil drilling industry that need it displayed in 12-hour format.
Pardon my French, but that's usually pure BS. How time calculations are affected by the way you display it? Regardless of what clock mode user uses your result will be the same. If not, then your app is broken an that should be fixed.
EDIT
TextClock is pretty simple widget. If current implementation does not fit your needs, write your own. You can even reuse current code TextClock.java
I'm creating a sqlite database from my c# project which will be used in my android application later on.
I have a CreateDate column in my sqlite database which I will need to get records ordered by this column later in my android application. Now my question is that is it better to save the date time as TEXT with YYYY-MM-DD HH:MM:SS format or I just convert all my dates into miliseconds and order them easily later since it's just a number?
Which one is easier to be ordered later in mobile application? or maybe my approaches are wrong so please feel free to shoot me with some best practices for this situation.
Thanks in advance.
Well unix timestamp looks simple and easier but i wont recommend you this.
Check out this gif.
What happens on January 19, 2038?
On this date the Unix Time Stamp will cease to work due to a 32-bit overflow. Before this moment millions of applications will need to either adopt a new convention for time stamps or be migrated to 64-bit systems which will buy the time stamp a "bit" more time.
Therefore i would suggest you to stick with YYYY-MM-DD HH:MM:SS format as it is both C# and Android compatible(or parseable i should say) and neither would string overflow in near future ;)
Good Luck.
I have web application in which I have to draw a chart according to time.
Now because the Daylight time is changing to standard time on 3rd November at 2AM.
I have change the code according to these time changes, but I want to know some API which tell me this date and time when these changes occur. Like "3rd November at 2AM".
Joda-Time is a great solution. Check this.
I'm working on a GWT app where I need to support the following scenario:
The server is located in time zone A
The client's browser is set to time zone B
The GWT app is configured to display date/time in time zone C
Since GWT does not support Calendar and the native support for time
zones in javascript is non-existent I can't think of a nice and clean
solution to this problem.
Have any of you done something similar or do you know of any good
utils I could use?
Thanks!
In my experience, the following best practice significantly reduces complexity and confusion when dealing with dates and timezones in gwt:
Whenever operating/storing dates within the application, treat all dates as milliseconds since epoch in GMT timezone. You can store them as string or int, it doesn't really make a difference.
Whenever displaying the date to the end user, format the date using appropriate timezone.
For your case, when you create a date on the Server (timezone A) convert it to milliseconds since epoch in GMT before sending it to the Client. On the client, use DateTimeFormat (or write your own date formatter util) to convert it into either timezone B or timezone C as appropriate.
You can't change the GWT timezone, hence all java.util.Date's has the browser timezone. You will need to handle the current timezone setting manually.
I see 3 options:
You manage the timezone conversion yourself.
You override the serializer/deserializer of java.util.Date like in this post. And maybe using a custom java.util.Date implemtation, that overrides the getTimezoneOffset(). This approach requires recompilation of the GWT API!.
You implement your own Date, either by extending java.util.Date (like in option 2) or wrapping it with some timezone object. In this option CustomFieldSerializer's may still be usefull, but there is no need for recompiling the GWT API.
I would prefer option 3. At least until GWT RPC maybe someday will support for overriding the CustomFieldSerializer's
Usefull date/time formatting hints.
Dave Paroulek's answer is the right approach. If you want to see an example of this, we created widgets that work independent of TimeZone and process the values on the server-side where we have all of the TimeZone information we need.
UTCDateBox - Wrapper around the GWT DateBox and always chooses the date at midnight in GMT and represents the value as a Long instead of a Date.
UTCTimeBox - New widget that always chooses a time as millis since midnight, independent of timezone, also represented as a Long.
UTCDateTimeUtils - Server-side code that splits a Date into 2 Long values appropriate for UTCDateBox and UTCTimeBox in a given TimeZone and combines them back into a Date in a given TimeZone.
Here is an example of the date the time controls being used together.
Blog article describing their implementation.
These widgets are available on GitHub.
I'm assuming you are using RPC calls for server-client communication here. Also assuming that you don't care about timezone B, and you know what timezone C is on the server.
You have a few options here:
Calculate the desired date in the server (no Java limits on what you can do there) and send it in a String to be displayed to the client, so you don't have to do anymore transformations on the client.
or:
Calculate the offset between timezone A and C on the server, apply it to all the Date objects you are passing to the client and just display them on the client.
if for some reason none of these were valid for you
Calculate the offset, send it to the client and apply it to any Date you receive from the server by transforming to ms, adding the offset and then creating a Date object again.
see this demo project
GWT timezone demo project
I created a GWT-compatible Java version of the jsTimezoneDetect Javascript library specifically for this purpose. This should provide a (very good guess of) the timezone name purely on the client side. Feel free to try it out and let me know if it works or doesn't work for you.