Search code examples
javasimpledateformat

simpledateformat format new Date() and then parse again return a different date


SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMDD");
            logger.info("new Date()="+new Date());
            Date today = sdf.parse(sdf.format(new Date()));
            logger.info("today:"+today + ", today.getTime():" + today.getTime());

result:

new Date()=Fri Sep 30 09:45:07 HKT 2022

today:Sun Dec 26 00:00:00 HKT 2021, today.getTime():1640448000000

as above, why format and then parse the same date, will return a different date?


Solution

  • Your formatting pattern is wrong. The code letters are case-sensitive. So fix your use of uppercase and lowercase.

    You are using terrible date-time classes that were years ago supplanted by modern java.time classes defined in JSR 310.

    To capture the current date, use LocalDate. Specify the desired time zone as the date varies around the globe by time zone. Note that LocalDate does not contain a time zone. The zone is used only to determine the current date.

    LocalDate today = LocalDate.now( ZoneId.of( "Africa/Tunis" ) ) ;
    

    Generate text in standard ISO 8601 format, year, month, and day, separated by a hyphen.

    String s = today.toString() ; 
    

    Parse.

    LocalDate ld = LocalDate.parse( s ) ;
    

    Search Stack Overflow to learn more. All of this has been covered many times before.