Regis Santos
Regis Santos

Reputation: 3749

Calculating difference in days between dates

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

Upvotes: 1

Views: 1221

Answers (1)

Renato Lochetti
Renato Lochetti

Reputation: 4568

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!

Upvotes: 8

Related Questions