-2
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?

user1169587
  • 1,104
  • 2
  • 17
  • 34
  • 5
    `"YYYYMMDD"` does not do what you think it does. Print the output of `sdf.format(new Date())` to find out. – f1sh Sep 30 '22 at 06:28

1 Answers1

4

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • 1
    If the OP wants the format YYYYMMDD, they can use `today.format(DateTimeFormatter.BASIC_ISO_DATE)` and parse back using `LocalDate.parse(today.format(DateTimeFormatter.BASIC_ISO_DATE), DateTimeFormatter.BASIC_ISO_DATE)`. – Ole V.V. Oct 01 '22 at 10:49