In my backend I am using Springboot.
I want to be able to set the server time to be EST so that when I do something like:
Date()
that time is in EST. Is that possible?
In my backend I am using Springboot.
I want to be able to set the server time to be EST so that when I do something like:
Date()
that time is in EST. Is that possible?
TL;DR: No, that is not possible.
Messages:
Date
, that class cannot hold a time zone, which obviously prevents what you are asking.Use ZonedDateTime
for a date and time with a time zone
ZoneId eastern = ZoneId.of("Australia/Victoria");
ZonedDateTime now = ZonedDateTime.now(eastern);
System.out.println(now);
Output when running just now:
2020-07-08T02:54:50.528310+10:00[Australia/Victoria]
This time is in Australian Eastern Standard Time, abbreviated either AEST or just EST. However, if you run the code after October 4, you will get Australian Eastern Daylight Time instead (AEDT, EDT or EDST).
If you intended North American Eastern Standard Time, you may try America/Toronto
or America/New_York
. They will give you EDT now and EST after 1st November.
There are time zones that will give you Eastern Standard Time all year, though, for example Australia/Brisbane
in Australia and America/Cancun
in North America.
ZonedDateTime
is part of java.time, the modern Java date and time API. I recommend that you always use java.time, never the poorly designed and long outdated Date
class.
Links
You can't change server machine's timezone from Java. If you want to do that on a server level, then you might want to consult server settings; however, if you're seeking to solve this at the application level, you can register a bean of the formatted Date object in the Spring Context
, and then inject it everywhere you wish.
Note, that if it's java.util.Date
, then you should use the DateFormat
instance and set the desired timezone in it. Then you use that object in your Date instance. Date class, on its own, does not contain any timezone information so you can't set the timezone on a Date object.