Calculating difference in days between dates

前端 未结 1 407
耶瑟儿~
耶瑟儿~ 2021-01-16 03:16

In my code the difference between dates is wrong, because it should be 38 days instead of 8 days. How can I fix?

package random04diferencadata;

import java.         


        
相关标签:
1条回答
  • 2021-01-16 03:57

    The problem is in the SimpleDateFormat variable. Months are represented by Capital M.

    Try change to:

    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm dd/MM/yyyy");
    

    For more, see this javadoc.

    Edited:

    And here is the code if you want to print the difference the way you commented:

        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm dd/MM/yyyy");
        try {
            Date date1 = sdf.parse("00:00 02/11/2012");
            Date date2 = sdf.parse("10:23 10/12/2012");
            long differenceMilliSeconds = date2.getTime() - date1.getTime();
            long days = differenceMilliSeconds / 1000 / 60 / 60 / 24;
            long hours = (differenceMilliSeconds % ( 1000 * 60 * 60 * 24)) / 1000 / 60 / 60;
            long minutes = (differenceMilliSeconds % ( 1000 * 60 * 60)) / 1000 / 60;
            System.out.println(days+" days, " + hours + " hours, " + minutes + " minutes.");
        } catch (ParseException e) {
            e.printStackTrace();
        }
    

    Hope this help you!

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