String to Date conversion returning wrong value

前端 未结 5 1117
感动是毒
感动是毒 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:23

    Day of the month is made using lowercase 'd', and you're using it uppercase...

    Change it to:

    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    

    at it will work

    0 讨论(0)
  • 2021-01-21 04:26

    One issue I see is:

    DateFormat formatter = new SimpleDateFormat("yyyy-MM-DD"); 
    

    should be:

    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); 
    

    DD represents Day in YEAR. Read this for more information on SimpleDateFormat.

    0 讨论(0)
  • 2021-01-21 04:27

    Change the DD for dd;

    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); 
    
    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2021-01-21 04:35

    Replace DD with dd to match the date.

    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    

    As per the SimpledateFormat documentation

    D Day in year

    d Day in month

    0 讨论(0)
提交回复
热议问题