atanu2destiny
atanu2destiny

Reputation: 1

How to tackle daylightsaving time of UK in a server running in CET like netherlands

Our server is running in netherlands but users uses the application in UK .

For UK 2017-03-26 02:30:00 is valid date-time but not in Netherlands.

I am using the code to convert the time by setting the timezone . But its not giving me right output.

    String toDate ="2017-03-26 02:30:00";//Valid Time in UK
    Date date = new Date();
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    // Use London's time zone to format the date in
    df.setTimeZone(TimeZone.getTimeZone("London"));

    System.out.println("Date and time in London: " + df.parse(toDate));

Output from Program : Date and time in London: Sun Mar 26 04:30:00 CEST 2017

Output Required : Date and time in London: Sun Mar 26 02:30:00 CEST 2017

Java version used : 1.7 . Can not use joda time for some dependency.

Upvotes: 0

Views: 200

Answers (1)

Anonymous
Anonymous

Reputation: 86324

First a detail, TimeZone.getTimeZone() is dangerous, if it doesn’t recognize the ID string, it will tacitly give you GMT. Exactly in London this is so close to the correct you may get fooled for a while. TimeZone.getTimeZone("London") gives you UTC (or GMT). As Stefan Freitag pointed out, it has to be TimeZone.getTimeZone("Europe/London") for the correct British time zone.

Next a very common misunderstanding: A Date object does not have a time zone in it. It’s a point in time only. So how come it is printed as Sun Mar 26 04:30:00 CEST 2017, where CEST obviously refers to a time zone (Central European Summer Time, used in the Netherlands)? When printing the date, you are implicitly invoking Date.toString(). This methods unconditionally prints the time according the default time zone for the JVM. Therefore, setting the time zone for the DateFormat you used for parsing has no effect here. And therefore changing the JVM’s time zone setting, as Hugo did in a comment, works. The other way of getting correct output for British users is to format the Date back into a string using a DateFormat with British time zone.

If you use Hugo’s trick in the beginning, before creating the DateFormat, it too will have the British time zone, and you need not call df.setTimeZone() (but you may if you think it makes the code clearer, of course).

Look forward to using Java 8 or later some day. The new date and time classes in java.time generally don’t come with the surprises experienced with the old ones.

Upvotes: 2

Related Questions