可能重复:
Calculating the Difference Between Two Java Date Instances
在Java中,我想计算两个日期之间的天数。
在我的数据库中,它们存储为DATE
数据类型,但在我的代码中它们是字符串。
我想计算这两个字符串之间的天数。
答案 0 :(得分:126)
首先,您必须仅在必要时将它们作为字符串处理。大多数情况下,您应该使用实际描述您正在使用的数据的数据类型来使用它们。
我建议您使用Joda Time,这是一个比Date
/ Calendar
更好的API。听起来你应该在这种情况下使用LocalDate
类型。然后您可以使用:
int days = Days.daysBetween(date1, date2).getDays();
答案 1 :(得分:39)
试试这段代码
Calendar cal1 = new GregorianCalendar();
Calendar cal2 = new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");
Date date = sdf.parse("your first date");
cal1.setTime(date)
date = sdf.parse("your second date");
cal2.setTime(date);
//cal1.set(2008, 8, 1);
//cal2.set(2008, 9, 31);
System.out.println("Days= "+daysBetween(cal1.getTime(),cal2.getTime()));
这个功能
public int daysBetween(Date d1, Date d2){
return (int)( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
}
答案 2 :(得分:39)
在Java 8.您可以使用Enum ChronoUnit
的实例来计算不同单位(天,月,秒)的时间量。
例如:
ChronoUnit.DAYS.between(startDate,endDate)
答案 3 :(得分:23)
我知道这个帖子现在已经两年了,我仍然没有在这里看到正确答案。
除非你想使用Joda或拥有Java 8,并且你需要减去受夏令时影响的日期。
所以我写了自己的解决方案。重要的一点是它只有在你真正关心日期时才有效,因为有必要丢弃时间信息,所以如果你想要25.06.2014 - 01.01.2010 = 1636
之类的东西,无论DST如何,这都应该有效:
private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd.MM.yyyy");
public static long getDayCount(String start, String end) {
long diff = -1;
try {
Date dateStart = simpleDateFormat.parse(start);
Date dateEnd = simpleDateFormat.parse(end);
//time is always 00:00:00, so rounding should help to ignore the missing hour when going from winter to summer time, as well as the extra hour in the other direction
diff = Math.round((dateEnd.getTime() - dateStart.getTime()) / (double) 86400000);
} catch (Exception e) {
//handle the exception according to your own situation
}
return diff;
}
因为时间总是00:00:00
,所以使用双倍然后Math.round()
应该有助于忽略从冬季到夏季时缺少的3600000毫秒(1小时),以及额外的小时从夏天到冬天。
这是我用来证明它的一个小型JUnit4测试:
@Test
public void testGetDayCount() {
String startDateStr = "01.01.2010";
GregorianCalendar gc = new GregorianCalendar(locale);
try {
gc.setTime(simpleDateFormat.parse(startDateStr));
} catch (Exception e) {
}
for (long i = 0; i < 10000; i++) {
String dateStr = simpleDateFormat.format(gc.getTime());
long dayCount = getDayCount(startDateStr, dateStr);
assertEquals("dayCount must be equal to the loop index i: ", i, dayCount);
gc.add(GregorianCalendar.DAY_OF_YEAR, 1);
}
}
...或者如果你想看看它的'生命'是什么,请用以下代码替换断言:
System.out.println("i: " + i + " | " + dayCount + " - getDayCount(" + startDateStr + ", " + dateStr + ")");
...这就是输出的样子:
i: 0 | 0 - getDayCount(01.01.2010, 01.01.2010)
i: 1 | 1 - getDayCount(01.01.2010, 02.01.2010)
i: 2 | 2 - getDayCount(01.01.2010, 03.01.2010)
i: 3 | 3 - getDayCount(01.01.2010, 04.01.2010)
...
i: 1636 | 1636 - getDayCount(01.01.2010, 25.06.2014)
...
i: 9997 | 9997 - getDayCount(01.01.2010, 16.05.2037)
i: 9998 | 9998 - getDayCount(01.01.2010, 17.05.2037)
i: 9999 | 9999 - getDayCount(01.01.2010, 18.05.2037)
答案 4 :(得分:10)
这是一个可以帮助你的小程序:
import java.util.*;
public class DateDifference {
public static void main(String args[]){
DateDifference difference = new DateDifference();
}
DateDifference() {
Calendar cal1 = new GregorianCalendar();
Calendar cal2 = new GregorianCalendar();
cal1.set(2010, 12, 1);
cal2.set(2011, 9, 31);
System.out.println("Days= "+daysBetween(cal1.getTime(),cal2.getTime()));
}
public int daysBetween(Date d1, Date d2) {
return (int)( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
}
}
答案 5 :(得分:7)
// http://en.wikipedia.org/wiki/Julian_day
public static int julianDay(int year, int month, int day) {
int a = (14 - month) / 12;
int y = year + 4800 - a;
int m = month + 12 * a - 3;
int jdn = day + (153 * m + 2)/5 + 365*y + y/4 - y/100 + y/400 - 32045;
return jdn;
}
public static int diff(int y1, int m1, int d1, int y2, int m2, int d2) {
return julianDay(y1, m1, d1) - julianDay(y2, m2, d2);
}
答案 6 :(得分:3)
我真的非常喜欢Java,所以我确信有更好的方法来做我提出的建议。
我有同样的需求,我使用两个日期的DAYOFYEAR之间的区别来做。 这似乎是一种更简单的方法...
我无法在性能和稳定性方面真正评估此解决方案,但我认为没问题。
这里:
public static void main(String[] args) throws ParseException { //Made this part of the code just to create the variables i'll use. //I'm in Brazil and the date format here is DD/MM/YYYY, but wont be an issue to you guys. //It will work anyway with your format. String s1 = "18/09/2014"; String s2 = "01/01/2014"; DateFormat f = DateFormat.getDateInstance(); Date date1 = f.parse(s1); Date date2 = f.parse(s2); //Here's the part where we get the days between two dates. Calendar day1 = Calendar.getInstance(); Calendar day2 = Calendar.getInstance(); day1.setTime(date1); day2.setTime(date2); int daysBetween = day1.get(Calendar.DAY_OF_YEAR) - day2.get(Calendar.DAY_OF_YEAR); //Some code just to show the result... f = DateFormat.getDateInstance(DateFormat.MEDIUM); System.out.println("There's " + daysBetween + " days between " + f.format(day1.getTime()) + " and " + f.format(day2.getTime()) + "."); }
在这种情况下,输出将是(记住我使用日期格式DD / MM / YYYY):
There's 260 days between 18/09/2014 and 01/01/2014.
答案 7 :(得分:2)
这个功能对我有好处:
public static int getDaysCount(Date begin, Date end) {
Calendar start = org.apache.commons.lang.time.DateUtils.toCalendar(begin);
start.set(Calendar.MILLISECOND, 0);
start.set(Calendar.SECOND, 0);
start.set(Calendar.MINUTE, 0);
start.set(Calendar.HOUR_OF_DAY, 0);
Calendar finish = org.apache.commons.lang.time.DateUtils.toCalendar(end);
finish.set(Calendar.MILLISECOND, 999);
finish.set(Calendar.SECOND, 59);
finish.set(Calendar.MINUTE, 59);
finish.set(Calendar.HOUR_OF_DAY, 23);
long delta = finish.getTimeInMillis() - start.getTimeInMillis();
return (int) Math.ceil(delta / (1000.0 * 60 * 60 * 24));
}
答案 8 :(得分:0)
我最好的解决方案(目前为止)用于计算差异天数:
// This assumes that you already have two Date objects: startDate, endDate
// Also, that you want to ignore any time portions
Calendar startCale=new GregorianCalendar();
Calendar endCal=new GregorianCalendar();
startCal.setTime(startDate);
endCal.setTime(endDate);
endCal.add(Calendar.YEAR,-startCal.get(Calendar.YEAR));
endCal.add(Calendar.MONTH,-startCal.get(Calendar.Month));
endCal.add(Calendar.DATE,-startCal.get(Calendar.DATE));
int daysDifference=endCal.get(Calendar.DAY_OF_YEAR);
但请注意,这假设不到一年的差异!
答案 9 :(得分:-7)
如果您厌倦了使用java,您可以将其作为查询的一部分发送到db2:
select date1, date2, days(date1) - days(date2) from table
将返回date1,date2以及两者之间的天数差异。