Search code examples
javatimezonesimpledateformat

SimpleDateFormat object changes timezone without adding/subtracting the correct number of hours


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


Solution

  • 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