How to get British Summertime Offset (BST) in Java

In the UK, I would like to get the current offset from UTC / GMT. Currently, the offset is 1 hour, but there seems to be no way to find this.

the code

TimeZone timeZone = TimeZone.getDefault(); logger.debug("Timezone ID is '" + timeZone.getID() + "'"); if (timeZone.getID().equals("GMT")) { timeZone = TimeZone.getTimeZone("Europe/London"); logger.debug("New timezone is '" + timeZone.getID() + "'"); } Long eventDateMillis = Long.parseLong(eventDateValue.getKeyValue()); int timezoneOffset = timeZone.getOffset(eventDateMillis); logger.debug("Offset for " + eventDateValue + "(" + eventDateMillis + ") using timezone " + timeZone.getDisplayName() + " is " + timezoneOffset); 

returns debug output

 Wed 2012/09/19 16:38:19.503|Debug|DataManagement|Timezone ID is 'GMT' Wed 2012/09/19 16:38:19.503|Debug|DataManagement|New timezone is 'GMT' Wed 2012/09/19 16:38:19.557|Debug|DataManagement|Offset for 18 Sep 2012 09:00(1347958800000) using timezone Greenwich Mean Time is 0 

In other words, the GMT time zone returns a zero offset, and I cannot find how to set it to return the correct offset.

If someone can provide a sample working code for JodaTime, it will do it, but I would really like it to not be necessary to install a separate library just for what should be single-line.

Java version is 7.

+6
source share
4 answers

In other words, the GMT time zone returns a zero offset, and I cannot find how to set it to return the correct offset.

0 is the correct offset for GMT, constantly.

You want Europe / London, which is a time zone that switches between GMT and BST.

EDIT: I did not initially notice that you are trying to get Europe / London. It seems that the time zone database used by the JVM is mostly confusing. You can either fix this or simply use Joda Time, which comes with its own copy of tzdb. Code example:

 DateTimeZone zone = DateTimeZone.forID("Europe/London"); long offset = zone.getOffset(new Instant()); System.out.println(offset); // 3600000 
+7
source

I just ran into this myself.

I tried TimeZone.getTimeZone ("London"); and it worked.

No, I have no idea why - "London" is not one of the identifiers returned by TimeZone ...

+1
source

Use timezone.getOffset (0) instead of timezone.getOffset (eventDateMillis).

This will give you an offset from January 1, 1970 GMT, which in the case of Europe / London is 3,600,000, not non-zero due to historical problems with Wales and Northern Ireland.

0
source

This made me a trick:

 String zone = "Europe/London"; int plusHoursGMT = TimeZone.getTimeZone(zone).getRawOffset() / 3600000; assertThat(plusHoursGMT, is(0)); 
0
source

Source: https://habr.com/ru/post/925785/


All Articles