views:

145

answers:

2
+1  Q: 

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

+2  A: 

You don't need a Calendar, only a TimeZone.

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

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.

Jon Skeet
Doesn't the UK use DST as well? In that case it differs from UTC, actually.
Joey
@Johannes Rössel: DST or not, the number of (milli)seconds elapsed since the epoch is unrelated to daylight saving time. If it's 6PM or 7PM does *NOT* change how many (milli)seconds elapsed since the epoch. Minutes aren't a fixed unit (you can have 59 or 61 seconds minutes), days aren't a fixed unit (you can have 23 or 25 hours day) but seconds and milliseconds are a fixed unit. This is precisely why you *always* should measure time in (milli)seconds and store dates/time in (milli)seconds since the epoch. And only do the conversion when displaying them to the end user.
Webinator