dogbane
dogbane

Reputation: 274738

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

Upvotes: 9

Views: 22805

Answers (3)

erickson
erickson

Reputation: 269797

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"));

Upvotes: 16

Marcus Leon
Marcus Leon

Reputation: 56699

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()));

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1502046

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.

Upvotes: 5

Related Questions