Get time in London

How can I get the current local time of a wall clock (in milliseconds since January 1, 1970) in London? Since my application can run on the server anywhere, I think I need to use the TimeZone Europe / London. I also need to take into account summer savings, that is, the application should add an hour during the "summer".

I would prefer to use the standard java.util libraries.

Is it correct?

TimeZone tz = TimeZone.getTimeZone("Europe/London") ; Calendar cal = Calendar.getInstance(tz); return cal.getTime().getTime() + tz.getDSTSavings(); 

thanks

+5
source share
3 answers

I am not sure what this quantity represents, since the β€œnumber of milliseconds since January 1, 1970” does not depend on location or daylight saving time. But perhaps this calculation will come in handy:

 TimeZone london = TimeZone.getTimeZone("Europe/London"); long now = System.currentTimeMillis(); return now + london.getOffset(now); 

Most applications are best served using UTC or local time; it is really neither one nor the other. You can find out UTC time and time in a certain zone, for example like this:

 Instant now = Instant.now(); /* UTC time */ ZonedDateTime local = now.atZone(ZoneId.of("Europe/London")); 
+12
source

Others said that it might not be a good idea to do this - I think it depends on your situation, but using UTC certainly has something to consider.

However, I think you missed something here: the number of seconds that occurred since January 1, 1970 UTC (as the Unix era is always determined), and in fact it is the same as in London, since the offset by this date was 0) available with any of these expressions:

 System.currentTimeMillis() new Date().getTime() Calendar.getInstance().getTime().getTime() 

If you think about it, the number of milliseconds from now on does not change depending on what time zone you are in.

Oh, and the normal suggestion is for a much better API with date and time, see Joda Time .

+4
source

To get the current time in London:

 SimpleDateFormat f = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z"); f.setTimeZone(TimeZone.getTimeZone("Europe/London")); System.out.println(f.format(GregorianCalendar.getInstance().getTime())); 
+2
source

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


All Articles