0

I have a String which represents a Date in the UTC timezone (because my database uses UTC). I want to convert this String into a date with SimpleDateFormat. The problem is that converts it into a Date in the CEST timezone without adding the 2 hour separating UTC and CEST. Here is the code:

//This is a date in UTC
String text = "2020-09-24T09:45:22.806Z";
//Here I define the correct format (The final Z means that it's UTC)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); 
//Then I parse it
Date date = sdf.parse(text);
//Then I print it
System.out.println(date);  

The result of the print is

Thu Sep 24 09:45:22 CEST 2020

Why CEST? I would like it to remain UTC, but if it has to become CEST at least add the 2 hours

nix86
  • 2,837
  • 11
  • 36
  • 69
  • 1
    "The problem is that converts it into a Date in the CEST timezone" - no it doesn't. There's no such thing as "a Date in the CEST time zone", because a java.util.Date doesn't *have* a time zone. (Instead, `toString()` always converts the instant-in-time represented in the `Date` to your system default time zone.) – Jon Skeet Sep 24 '20 at 11:08
  • 3
    As for why it's not handling the Z as you expect it to - you've put `'Z'` in the format, which means "the exact character Z" with no implication on the time zone. If you'd used `X` (unquoted) then it would have parsed it as an ISO-8601 time zone offset indicator. Fundamentally, if you can *possibly* move to java.time instead, you really should. – Jon Skeet Sep 24 '20 at 11:09
  • 1
    There's a way more related post to flag this post as duplicate : https://stackoverflow.com/questions/19112357/java-simpledateformatyyyy-mm-ddthhmmssz-gives-timezone-as-ist – IQbrod Sep 24 '20 at 11:19
  • I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead just use `Instant` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Sep 24 '20 at 17:08

1 Answers1

0

You should setTimeZone() to your DateFormat like

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class Main {
    public static void main(String[] args) throws ParseException {
        //This is a date in UTC
        String text = "2020-09-24T09:45:22.806Z";
        //Here I define the correct format (The final Z means that it's UTC)
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        //Then I parse it
        Date date = sdf.parse(text);
        //Then I print it
        System.out.println(date);
    }
}

I also replaced 'Z' to X following the documentation

IQbrod
  • 2,060
  • 1
  • 6
  • 28