String to Date conversion returning wrong value

前端 未结 5 1170
感动是毒
感动是毒 2021-01-21 03:49

I am trying to convert a String into Date... But the return value is wrong.

String startDate = \"2013-07-24\";
Date date = new Date();
try{         
    DateForm         


        
5条回答
  •  甜味超标
    2021-01-21 04:32

    Modern answer:

        String startDate = "2013-07-24";
        try {
            LocalDate date = LocalDate.parse(startDate);
            System.out.println(date);
        } catch (DateTimeParseException dtpe) {
            System.out.println(dtpe.getMessage());
        }
    

    It prints the same as the input string:

    2013-07-24
    

    Your string conforms with ISO 8601. This is what the modern Java date & time API known as java.time or JSR-310 “understands” natively, so there is no need for an explicit formatter. It is also what the toString methods of the classes generally produce, which is why you get the same output back. If you want output in a different format, use a DateTimeFormatter.

    I recommend leaving the outdated SimpleDateFormat and friends alone. What you really asked of it was a date that was in July and was the 24th day of the year. Obviously no such date exists, and it’s typical for SimpleDateFormat to give you some date anyway and pretend all is fine. I cannot count the questions on Stack Overflow that come out of such surprising behaviour of the outdated classes. The modern API is so much nicer to work with and does a much greater effort to tell you when you make mistakes (which we obviously all do).

提交回复
热议问题