日期

Calendar

 

DAY_OF_YEAR

Field number for get and set indicating the day number within the current year.  The first day of the year has value 1.

每个月的第一天用1表示

 

MONTH

Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year

月份的第一个用0表示,即一月份是用0表示

下面有两种方式计算两个日期之间的天数只差

package com.robert.Date;

import java.util.Calendar;

public class DateUtils {

	public static void main(String[] args) {
		Calendar calendar1 = Calendar.getInstance();
		calendar1.set(2013, 9, 8);
		Calendar calendar2 = Calendar.getInstance();
		calendar2.set(2010, 8, 16);
		System.out.println(getDays(calendar1, calendar2));
		System.out.println(getDays2(calendar1,calendar2));
	}

	/**
	 * 取得两个日期之间得天数
	 * @param date1	 前面的日期
	 * @param date2	 后面的日期
	 * @return
	 */
	public static int getDays(Calendar date1, Calendar date2) {
		int y1 = date1.get(Calendar.YEAR);
		int y2 = date2.get(Calendar.YEAR);
		int d1 = date1.get(Calendar.DAY_OF_YEAR);
		int d2 = date2.get(Calendar.DAY_OF_YEAR);
		return (y1-y2)*365+(d1 - d2);
	}
	
	/**
	 * 通过获取毫秒来计算天数之差
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static long getDays2(Calendar date1,Calendar date2){
		long time1 = date1.getTimeInMillis();
		long time2 = date2.getTimeInMillis();
		long diff = time1 - time2;
		long days = diff/(24*60*60*1000);
		return days;
	}
}

方式一的输出结果为:1117

方式二的输出结果为:1118

发现第一种方式错误!

有的年份是瑞年,所以出现了不同的结果,上述给出的日期区间内2012年为闰年。


 

原文地址:https://www.cnblogs.com/mengjianzhou/p/5986806.html