Search code examples
javadateparsingformatsimpledateformat

Parsing SimpleDateFormat a Date as "yyyy-MM-dd" is not working in a appropieted way


I am trying to parse this String date : "2020-06-25T07:48:32Z" to a Date like "2020-06-25" and I did a method like this :

        String newDateFormat = "yyyy-MM-dd";
                try {
                    Date newparseDate = new SimpleDateFormat(newDateFormat).parse(date);
                    System.out.println(newparseDate);
                    return new SimpleDateFormat(dateTimeFormatPattern).parse(date);
                } catch (ParseException px) {
                    px.printStackTrace();
                }
                return null;
            }
    

But I got this format: Thu Jun 25 00:00:00 CEST 2020


Solution

  • I strongly recommend you use the modern date-time API instead of the broken java.util date-time API.

    import java.time.LocalDate;
    import java.time.ZonedDateTime;
    
    public class Main {
        public static void main(String[] args) {
            ZonedDateTime zdt = ZonedDateTime.parse("2020-06-25T07:48:32Z");
            System.out.println(zdt);
    
            // Your required format can be got by simply using LocalDate which drops the
            // time-zone and offset information
            LocalDate ldt = zdt.toLocalDate();
            System.out.println(ldt);
        }
    }
    

    Output:

    2020-06-25T07:48:32Z
    2020-06-25
    

    However, if you still want to use the outdated date-time API, you can do it as follows:

    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    public class Main {
        public static void main(String[] args) throws ParseException {
            // Format for the given date-time string
            SimpleDateFormat oldDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    
            // Desired format
            SimpleDateFormat newDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    
            // The given date-time string
            String dateStr = "2020-06-25T07:48:32Z";
    
            // Parse to java.util.Date
            Date newParseDate = oldDateFormat.parse(dateStr);
    
            // Format to the desired format
            String newDateStr = newDateFormat.format(newParseDate);
            System.out.println(newDateStr);
        }
    }
    

    Output:

    2020-06-25