java如何判断两个日期字符串相差多少天

a = ‘20140301’
b = '20140225'
请问有没有什么函数可以直接将这两个字符串相减,减得的结果为4.
(2月25日和3月1日相差4天)

没有这样的函数,但是你自己可以封装一个这样的函数。
一般来说,并不计算两个日期相差的月数以及年数,因为月的天数以及年的天数并不是固定的,所以很多倒计时最多计算到天。
函数体:
SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
String a="20140301";
String b = "20140225";
Long c = sf.parse(b).getTime()-sf.parse(a).getTime();
long d = c/1000/60/60/24;//天
System.out.println(d+"天");
只要将a,b当做参数传过去,将天数返回就可以
温馨提示:答案为网友推荐,仅供参考
第1个回答  2019-03-15
/**
* 取得两个时间段的时间间隔 return t2 与t1的间隔天数 throws ParseException
* 如果输入的日期格式不是0000-00-00 格式抛出异常
*/
public static int getBetweenDays(String t1, String t2)
throws ParseException {
SimpleDateFormat 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 < betweenYears; i++) {
c1.set(Calendar.YEAR, (c1.get(Calendar.YEAR) + 1));
betweenDays += c1.getMaximum(Calendar.DAY_OF_YEAR);
}
return betweenDays;
}
第2个回答  2014-02-18
SimpleDateFormat smdf = new SimpleDateFormat( "yyyy-MM-dd ");
try {
Date start = smdf.parse( "2005-09-28 23:15 ");
Date end = smdf.parse( "2005-10-06 00:13 ");
long t = (end.getTime() - start.getTime()) / (3600 * 24 * 1000);
System.out.println(t);
} catch (ParseException e) {
e.printStackTrace();
}
第3个回答  2014-02-18
直接换算成毫秒相减 然后再除以一天毫秒数 就知道相差多少天了。
相似回答