user2261923
user2261923

Reputation: 11

calculating time difference when month changes

I have been trying to calculate the time difference between two dates to get it in minutes. The code below is what I have. But it is giving me negative value. Can anyone help me!!?

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


public class time {

/**
 * @param args
 * @throws ParseException 
 */
public static void main(String[] args) throws ParseException {
    // TODO Auto-generated method stub

    String time1 = "05/01/2010 11:59:00";
    String time2 = "04/30/2010 23:59:00";

    SimpleDateFormat sdf = new SimpleDateFormat("mm/dd/yyyy H:mm:ss");
    Date date1 = sdf.parse(time1);
    Date date2 = sdf.parse(time2);
    long difference = date1.getTime() - date2.getTime(); 
    System.out.println(difference/(3600*1000));
}

}

Upvotes: 1

Views: 102

Answers (2)

P. Lalonde
P. Lalonde

Reputation: 694

The date format you are using is mixing minutes and months.

You should use this format instead: MM/dd/yyyy HH:mm:ss

Also, the calculation is wrong, your are getting the difference in hours, if you want hours, you should use this: System.out.println((difference / 1000) / 60);

Upvotes: 3

Joachim Sauer
Joachim Sauer

Reputation: 308021

You must use MM instead of mm in your date format at the first position: mm is minutes, MM is months:

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

Upvotes: 8

Related Questions