Reputation:
I need a java.utils.TimeZone object that represents a UTC time zone (i.e. "UTC+4" in an object form). I tried the getTimeZone function, but it returns a GMT object.
val timeZone = TimeZone.getTimeZone("UTC+4:00")
print(timeZone)
outputs
sun.util.calendar.ZoneInfo[id="GMT",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
I have never worked with time zones and honestly I don't really understand them much, so if you could help me here that would be really appreciated
Upvotes: 0
Views: 1105
Reputation: 79425
The java.util
date-time API is outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.
There is a difference between time zone and time zone offset. What you have mentioned is a time zone offset, not a time zone. A time zone is unique and therefore it has an ID e.g. ZoneId.of("America/New_York")
whereas a time zone offset tells you about the amount of time by which a given time is offset from the UTC time. There can be many time zones falling on the same time zone offset. Check https://en.wikipedia.org/wiki/List_of_tz_database_time_zones to learn more about it.
Demo:
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
Instant instant = Instant.now();
System.out.println(instant);
ZoneOffset offset = ZoneOffset.of("+04:00");
OffsetDateTime odt = instant.atOffset(offset);
System.out.println(odt);
ZoneId zoneId = ZoneId.of("America/New_York");
ZonedDateTime zdt = instant.atZone(zoneId);
System.out.println(zdt);
}
}
Output:
2022-09-29T18:11:06.887943Z
2022-09-29T22:11:06.887943+04:00
2022-09-29T14:11:06.887943-04:00[America/New_York]
Learn more about the the modern date-time API from Trail: Date Time.
Upvotes: 1