Java: Difference between two dates spanning over months

前端 未结 4 1783
没有蜡笔的小新
没有蜡笔的小新 2021-01-06 06:31

I have the following code that successfully gets me the difference between two days (in days, hours, minutes, seconds):

SimpleDateFormat format = new SimpleD         


        
4条回答
  •  情歌与酒
    2021-01-06 07:09

    You are using

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");
    

    Should be

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    

    You'll get the correct result of

    Start: 2013-05-31 10:15:01
    End: 2013-08-01 11:22:33
    62 days, 1 hours, 7 minutes, 32 seconds
    

    Here's the javadoc for the date patterns. dd is day in month. DD is day in year. Your Date objects just weren't parsed the way you expected. Basically the day in year value of 31 was overwriting the month value.

    Debuggers are your friend.

提交回复
热议问题