1

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();
        }
    }
}
Mario S
  • 11,715
  • 24
  • 39
  • 47
Regis Santos
  • 3,469
  • 8
  • 43
  • 65
  • 2
    For this sort of calculation, you might want to use [JodaTime](http://joda-time.sourceforge.net/). You can create an [`Interval`](http://joda-time.sourceforge.net/api-release/org/joda/time/Interval.html) instance to represent a pair of from/to dates, then use `interval.toPeriod().getDays()` – millimoose Nov 03 '12 at 01:22
  • See my answser on a similar thread : http://stackoverflow.com/a/25651619/920345 – Hugues Sep 03 '14 at 18:52

1 Answers1

8

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!

Renato Lochetti
  • 4,558
  • 3
  • 32
  • 49