Java Date object from String not working properly

前端 未结 2 959
一生所求
一生所求 2021-01-18 02:26

I have run into a stubborn problem I cannot seem to solve. I have looked for solutions at stackoverflow and have found a lot of posts about Java date formatting, but nothing

相关标签:
2条回答
  • 2021-01-18 03:18

    You're using YYYY in your format specifier, which is week year (See SimpleDateFormat). You need yyyy, which is just "year".

    I suspect the wrong result was out because you also specified the month and day, which aren't really "features" in the week year. When you use week year, you'd specify the "week of week year" and "day of week", it might have given some more sensible results, but obviously you didn't really meant to use week years.

    I recommend you to specify your Locale in your code. Of course it will run perfectly on your machine, but it may cause an unparsable date exception somewhere else like China.

    DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
    
    0 讨论(0)
  • 2021-01-18 03:22

    Use yyyy not YYYY in your format string.

    YYYY is a very special thing, the calendar week year.

    See the SimpleDateFormat documentation for more info.

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