Difference Between two Time in Minutes

DifferenceBetween2TimeinMin.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.passionatecodes.timediff;

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

public class DifferenceBetween2TimeinMin {
 
 public static void main(String args[]) throws ParseException
 {              
     SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy HH-mm-ss");
     
     Date date = dateFormatter.parse("20/04/2017 14-51-11");
     Date date2 = dateFormatter.parse("20/04/2017 14-52-12");
    
  long abc=DifferenceBetween2TimeinMin.getDateDiff(date, date2, TimeUnit.MINUTES); //TimeUnit.SECONDS
  System.out.println("Time in min: "+abc);
 }
 
 /**
  * Get a diff between two dates
  * @param date1 the oldest date
  * @param date2 the newest date
  * @param timeUnit the unit in which you want the diff
  * @return the diff value, in the provided unit
  */
 public static long getDateDiff(Date date1, Date date2, TimeUnit timeUnit) {
     long diffInMillies = date2.getTime() - date1.getTime();
     return timeUnit.convert(diffInMillies,TimeUnit.MILLISECONDS);
 }
}

Output:
Time in min: 1

No comments:

Post a Comment