计算日期之间的天数差异

时间:2012-11-03 01:16:48

标签: java date

在我的代码中,日期之间的差异是错误的,因为它应该是38天而不是8天。我该如何解决?

package random04diferencadata;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Random04DiferencaData {

    /**
     * http://www.guj.com.br/java/9440-diferenca-entre-datas
     */
    public static void main(String[] args) {
        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();
            System.out.println("diferenca em milisegundos: " + differenceMilliSeconds);
            System.out.println("diferenca em segundos: " + (differenceMilliSeconds / 1000));
            System.out.println("diferenca em minutos: " + (differenceMilliSeconds / 1000 / 60));
            System.out.println("diferenca em horas: " + (differenceMilliSeconds / 1000 / 60 / 60));
            System.out.println("diferenca em dias: " + (differenceMilliSeconds / 1000 / 60 / 60 / 24));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

1 个答案:

答案 0 :(得分:8)

问题出在SimpleDateFormat变量中。几个月由Capital M.代表。

尝试更改为:

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

有关详情,请参阅此javadoc.

<强>编辑:

如果你想以你评论的方式打印差异,这就是代码:

    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();
    }

希望这对你有帮助!