java計算間隔天數

longerandlonger發表於2012-10-24

來源:http://pure.iteye.com/blog/485989


程式碼:

public static Long getDaysBetween(Date startDate, Date endDate) {
		Calendar fromCalendar = Calendar.getInstance();
		fromCalendar.setTime(startDate);
		fromCalendar.set(Calendar.HOUR_OF_DAY, 0);
		fromCalendar.set(Calendar.MINUTE, 0);
		fromCalendar.set(Calendar.SECOND, 0);
		fromCalendar.set(Calendar.MILLISECOND, 0);

		Calendar toCalendar = Calendar.getInstance(); // 沒必要例項化兩個Calendar !!!
		toCalendar.setTime(endDate);
		toCalendar.set(Calendar.HOUR_OF_DAY, 0);
		toCalendar.set(Calendar.MINUTE, 0);
		toCalendar.set(Calendar.SECOND, 0);
		toCalendar.set(Calendar.MILLISECOND, 0);

		return (toCalendar.getTime().getTime() - fromCalendar.getTime().getTime()) / (1000 * 60 * 60 * 24);
	}


	public static Long getDaysBetween(Date startDate, Date endDate) {
		Calendar calendar = CAL_INSTANCE.get();
		calendar.setTime(startDate);
		cleanHHmmss(calendar);
		
		long fromTime = calendar.getTime().getTime();

		calendar.setTime(endDate);
		cleanHHmmss(calendar);
		
		long toTime = calendar.getTime().getTime();
		
		return (fromTime - toTime) / MILLISECONDS_A_DAY;
	}
	
	private static final ThreadLocal<Calendar> CAL_INSTANCE = new ThreadLocal<Calendar>() {
		
		@Override
		protected Calendar initialValue() {
			return Calendar.getInstance(TimeZone.getTimeZone("GMT+8:00"));
		}
		
	};

相關文章