日期

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年为闰年。

 

 


 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值