Get the Difference between 2 Times

91 views Asked by At

i'm trying the get the Difference between 2 dates time.. i have an arraylist, each object contains data of type Date..

My Questions are: 1) is using Calendar.getInstance().get(Calendar.MINUTE) ... etc the best way to get the current date & Time 2) should i fill manually the data in variable of Date, as follows:

Date currentDate = new Date();
currentDate.setMinutes(Calendar.getInstance().get(Calendar.MINUTE));
currentDate.setHours(Calendar.getInstance().get(Calendar.HOUR));
currentDate.setDate(Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
currentDate.setMonth(Calendar.getInstance().get(Calendar.MONTH));
currentDate.setYear(Calendar.getInstance().get(Calendar.YEAR));

3) How to get the Difference between the currentDate and the an old date i have is it like currentDate - oldDate and what about the "AM_PM" issue, should i do this function manually?

3

There are 3 answers

0
James Wierzba On

1) is using Calendar.getInstance().get(Calendar.MINUTE) ... etc the best way to get the current date

JavaDoc from java.util.Date empty constructor:

Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.

3) How to get the Difference between the currentDate and the an old date i have is it like currentDate - oldDate and what about the "AM_PM" issue, should i do this function manually?

Date oldDate = ...
Date currentDate = new Date();
long dt = currentDate.getTime() - oldDate.getTime();
0
Davide Lorenzo MARINO On

1) To get the current date:

Date = new Date();

2) TO set manually a Date it is better to work with a Calendar.

Calendar c = new GregorianCalendar();
c.set(Calendar.MONTH, 1);
c.set(Calendar.YEAR, 2015);
// ... and so on
Date date = c.getTime();

3) to calculate the distance in ms between two dates.

Date d1 = ....;
Date d2 = ....;
long distance = d1.getTime() - d2.getTime();
0
Sachin Thapa On

Try this, variable now below is current date.

String givenDate = "03/11/2015";

          SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
          try {
                 Date date = (Date)dateFormat.parseObject(givenDate);
                 Date now = new Date();
                 System.out.println(date);
                 System.out.println(now);
                 int diffInDays = (int)( (now.getTime() - date.getTime()) 
                    / (1000 * 60 * 60 * 24) );

                 System.out.println(diffInDays);

          } catch (ParseException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
          }

You can choose any format and add time or AM/PM, see more details of SimpleDateFormat. If you dont have string dates then you can directly use date variable shown above.

Cheers !!