java中怎么通过日期算出天数_java中计算两日期间隔天数的简单示例

package com.color.program;

import java.text.DateFormat;

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Calendar;

import java.util.Date;

public class CompareTime {

public static void main(String[] args){

String t1 = "2008-05-09";

String t2 = "2008-5-13";

try {

System.out.println(CompareTime.getBetweenDays(t1, t2));

} catch (ParseException e) {

e.printStackTrace();

}

}

/**

* 取得两个时间段的时间间隔

* return t2 与t1的间隔天数

* throws ParseException 如果输入的日期格式不是0000-00-00 格式抛出异常

*/

public static int getBetweenDays(String t1,String t2) throws ParseException{

DateFormat format = new SimpleDateFormat("yyyy-MM-dd");

int betweenDays = 0;

Date d1 = format.parse(t1);

Date d2 = format.parse(t2);

Calendar c1 = Calendar.getInstance();

Calendar c2 = Calendar.getInstance();

c1.setTime(d1);

c2.setTime(d2);

// 保证第二个时间一定大于第一个时间

if(c1.after(c2)){

c1 = c2;

c2.setTime(d1);

}

int betweenYears = c2.get(Calendar.YEAR)-c1.get(Calendar.YEAR);

betweenDays = c2.get(Calendar.DAY_OF_YEAR)-c1.get(Calendar.DAY_OF_YEAR);

for(int i=0;i

c1.set(Calendar.YEAR,(c1.get(Calendar.YEAR)+1));

betweenDays += c1.getMaximum(Calendar.DAY_OF_YEAR);

}

return betweenDays;

}

}

posted on 2008-09-24 16:58 冶人 阅读(5326) 评论(9)  编辑  收藏

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值