Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Time in London

How can I get the current local wall clock time (in number of millis since 1 Jan 1970) in London? Since my application can run on a server in any location, I think I need to use a TimeZone of "Europe/London". I also need to take Daylight Savings into account i.e. the application should add an hour during the "summer".

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

Is this correct?

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

Thanks

like image 681
dogbane Avatar asked Mar 29 '10 18:03

dogbane


People also ask

Is GMT time zone London?

London uses Greenwich Mean Time (GMT) during standard time and British Summer Time (BST) during Daylight Saving Time (DST), or summer time.


2 Answers

I'm not sure what this quantity represents, since the "number of millis since 1 Jan 1970" doesn't vary based on location or daylight saving. But, perhaps this calculation is useful to you:

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

Most applications are better served using either UTC time or local time; this is really neither. You can get the UTC time and time in a particular zone like this:

Instant now = Instant.now(); /* UTC time */
ZonedDateTime local = now.atZone(ZoneId.of("Europe/London"));
like image 65
erickson Avatar answered Sep 24 '22 05:09

erickson


Others have said that it may well not be a good idea to do this - I believe it depends on your situation, but using UTC is certainly something to consider.

However, I think you've missed something here: the number of seconds which have occurred since January 1st 1970 UTC (which is how the Unix epoch is always defined - and is actually the same as in London, as the offset on that date was 0) is obtainable with any of these expressions:

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

If you think about it, the number of milliseconds since that particular instant doesn't change depending on which time zone you're in.

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

like image 23
Jon Skeet Avatar answered Sep 24 '22 05:09

Jon Skeet