Hàm Java tính sự khác biệt giữ hai ngày quy ra ngày hoặc giờ hoặc phút hoặc giây hoặc microseconds hoặc nanoseconds.

Java function calculating the difference between two java date return days, hours, microseconds, microseconds, minutes, nanoseconds, seconds. Đây là một hàm Java dựng sẵn dùng để tính toán thời gian khác biệt giữ hai đối tượng ngày trong Java, thời gian khác biệt này có thể được quy đổi ra thành ngày hoặc giờ hoặc phút hoặc giây hoặc microseconds hoặc nanoseconds.

Java Function: Get a diff between two dates:

/**
* 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 like Day, Hours, Min...
* @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);
}


Example:

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package z.test;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
*
* @author bnson
* @web vnlives.net
*/
public class CalculatingTheDifferenceBetweenTwoDate {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println(getDateDiff(new Date(2014, 10, 10),new Date(2014, 10, 10),TimeUnit.DAYS));
}

/**
* 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 like Day, Hours, Min...
* @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);
}

}



No comments:

Post a Comment