1

在我的代码中,日期之间的差异是错误的,因为它应该是 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();
        }
    }
}
4

1 回答 1

8

问题出在SimpleDateFormat变量中。月份用大写 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();
    }

希望这对你有帮助!

于 2012-11-03T01:19:37.227 回答