0

I want to convert A UTC date to CEST and vice versa. The below is the date

2018-09-05T13:30:10,980.

What is the approach to this ?

This is what i have done from another example. I want to check that if this is correct way of doing it or we can use any Java 8 feature recommendation

DateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss','SSS");
    utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

    Date date = utcFormat.parse("2018-08-22T08:54:43,907");

    DateFormat pstFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss','SSS");
    pstFormat.setTimeZone(TimeZone.getTimeZone("CET"));

    System.out.println(pstFormat.format(date));
Java Programmer
  • 1,347
  • 3
  • 12
  • 31
  • Use ```OffsetDateTime```. What you put in is always UTC and you can set an offset for it to be CET or anything else really. – Max Sep 06 '18 at 09:45
  • I recommend you avoid the `SimpleDateFormat` class. It is not only long outdated, it is also notoriously troublesome. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/), what you refer to as “any Java 8 feature”. – Ole V.V. Sep 06 '18 at 10:08
  • Also avoid relying on three and four letter time zone abbreviations. Very many of them are ambiguous, so you don’t know what you get. And CET is not a true time zone. Use for example Europe/Oslo or Europe/Rome, depending on what is appropriate for you. – Ole V.V. Sep 06 '18 at 10:11
  • @OleV.V. i didn't get that point. Instead of CET i have to use Europe/Rome ? if i am based in Rome – Java Programmer Sep 07 '18 at 10:40
  • It’s a recommendation, you can do as it pleases you. Assuming you are based in Rome, you’d be on CEST, not CET, on August 22, and I as a reader wouldn’t know which of the two to expect from your code. Also if the time had been from back when Spain and Poland didn’t share the same time, I wouldn’t know what to expect. I recommend you state that explicitly to avoid confusing your reader. – Ole V.V. Sep 07 '18 at 10:50

0 Answers0