持续时间或两个日期之间的差额

Java示例,用于计算两个日期实例(Date和LocalDate类)之间的持续时间或差异。

两个LocalDate实例之间的持续时间

使用Duration.between()方法获得两个本地日期实例之间的差异。

//First LocalDate
LocalDate today = LocalDate.now();		//1

//Second LocalDate
LocalDate sameDayNextMonth = LocalDate.now().plusMonths(1);		//2

//Difference between dates
Duration duration = Duration.between( today.atStartOfDay(), 
				sameDayNextMonth.atStartOfDay() );

//Verify differences
duration.toDays();			//31
duration.toHours();			//744
duration.toMinutes();		//44640
duration.toSeconds();		//2678400
duration.toMillis();		//2678400000

两个Date实例之间的差异

使用Duration.between()方法获得两个日期实例之间的差异。

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

public class Main 
{
	public static void main(String[] args) 
	{
		//First Date
		Date today = new Date();
		
		//Second Date
		Date sameDayNextMonth = new Date();
		sameDayNextMonth.setMonth(today.getMonth() + 1);
		
		long days = getDateDiff (today, sameDayNextMonth, TimeUnit.DAYS);			//31
		long hours = getDateDiff (today, sameDayNextMonth, TimeUnit.HOURS);			//744
		long minutes = getDateDiff (today, sameDayNextMonth, TimeUnit.MINUTES);		//44640
		long seconds = getDateDiff (today, sameDayNextMonth, TimeUnit.SECONDS);		//2678400
		long mills = getDateDiff (today, sameDayNextMonth, TimeUnit.MILLISECONDS);	//2678400000
	}
	
	public static long getDateDiff(Date date1, Date date2, TimeUnit timeUnit) 
	{
	    long diffInMillies = date2.getTime() - date1.getTime();
	    
	    return timeUnit.convert(diffInMillies, TimeUnit.MILLISECONDS);
	}
}

学习愉快!

  1. 持续时间Javadoc
  2. LocalDate Javadoc
  3. 日期Javadoc

saigon has written 1440 articles

Leave a Reply