81

我需要找到两个日期之间的天数:一个来自报告,一个是当前日期。我的片段:

  int age=calculateDifference(agingDate, today);

calculateDifference是一个私有方法,agingDate并且todayDate对象,仅供您澄清。我关注了来自 Java 论坛的两篇文章Thread 1 / Thread 2

它在独立程序中运行良好,尽管当我将其包含在我的逻辑中以从报告中读取时,我得到了不同寻常的值差异。

为什么会发生,我该如何解决?

编辑 :

与实际天数相比,我得到的天数更多。

public static int calculateDifference(Date a, Date b)
{
    int tempDifference = 0;
    int difference = 0;
    Calendar earlier = Calendar.getInstance();
    Calendar later = Calendar.getInstance();

    if (a.compareTo(b) < 0)
    {
        earlier.setTime(a);
        later.setTime(b);
    }
    else
    {
        earlier.setTime(b);
        later.setTime(a);
    }

    while (earlier.get(Calendar.YEAR) != later.get(Calendar.YEAR))
    {
        tempDifference = 365 * (later.get(Calendar.YEAR) - earlier.get(Calendar.YEAR));
        difference += tempDifference;

        earlier.add(Calendar.DAY_OF_YEAR, tempDifference);
    }

    if (earlier.get(Calendar.DAY_OF_YEAR) != later.get(Calendar.DAY_OF_YEAR))
    {
        tempDifference = later.get(Calendar.DAY_OF_YEAR) - earlier.get(Calendar.DAY_OF_YEAR);
        difference += tempDifference;

        earlier.add(Calendar.DAY_OF_YEAR, tempDifference);
    }

    return difference;
}

笔记 :

不幸的是,没有一个答案能帮助我解决问题。我在Joda-time库的帮助下解决了这个问题。

4

19 回答 19

149

我建议你使用优秀的Joda Time库而不是有缺陷的 java.util.Date 和朋友。你可以简单地写

import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.Days;

Date past = new Date(110, 5, 20); // June 20th, 2010
Date today = new Date(110, 6, 24); // July 24th 
int days = Days.daysBetween(new DateTime(past), new DateTime(today)).getDays(); // => 34
于 2010-07-21T14:03:58.540 回答
48

我加入游戏可能为时已晚,但到底是什么啊?:)

您认为这是线程问题吗?例如,您如何使用此方法的输出?或者

我们可以更改您的代码以执行以下简单操作:

Calendar calendar1 = Calendar.getInstance();
    Calendar calendar2 = Calendar.getInstance();
    calendar1.set(<your earlier date>);
    calendar2.set(<your current date>);
    long milliseconds1 = calendar1.getTimeInMillis();
    long milliseconds2 = calendar2.getTimeInMillis();
    long diff = milliseconds2 - milliseconds1;
    long diffSeconds = diff / 1000;
    long diffMinutes = diff / (60 * 1000);
    long diffHours = diff / (60 * 60 * 1000);
    long diffDays = diff / (24 * 60 * 60 * 1000);
    System.out.println("\nThe Date Different Example");
    System.out.println("Time in milliseconds: " + diff
 + " milliseconds.");
    System.out.println("Time in seconds: " + diffSeconds
 + " seconds.");
    System.out.println("Time in minutes: " + diffMinutes 
+ " minutes.");
    System.out.println("Time in hours: " + diffHours 
+ " hours.");
    System.out.println("Time in days: " + diffDays 
+ " days.");
  }
于 2010-07-29T16:47:26.470 回答
23

diff / (24 * etc) 不考虑时区,因此如果您的默认时区中包含 DST,它可能会导致计算失败。

这个链接有一个很好的小实现。

以下是上述链接的来源,以防链接断开:

/** Using Calendar - THE CORRECT WAY**/  
public static long daysBetween(Calendar startDate, Calendar endDate) {  
  //assert: startDate must be before endDate  
  Calendar date = (Calendar) startDate.clone();  
  long daysBetween = 0;  
  while (date.before(endDate)) {  
    date.add(Calendar.DAY_OF_MONTH, 1);  
    daysBetween++;  
  }  
  return daysBetween;  
}  

/** Using Calendar - THE CORRECT (& Faster) WAY**/  
public static long daysBetween(final Calendar startDate, final Calendar endDate)
{
  //assert: startDate must be before endDate  
  int MILLIS_IN_DAY = 1000 * 60 * 60 * 24;  
  long endInstant = endDate.getTimeInMillis();  
  int presumedDays = 
    (int) ((endInstant - startDate.getTimeInMillis()) / MILLIS_IN_DAY);  
  Calendar cursor = (Calendar) startDate.clone();  
  cursor.add(Calendar.DAY_OF_YEAR, presumedDays);  
  long instant = cursor.getTimeInMillis();  
  if (instant == endInstant)  
    return presumedDays;

  final int step = instant < endInstant ? 1 : -1;  
  do {  
    cursor.add(Calendar.DAY_OF_MONTH, step);  
    presumedDays += step;  
  } while (cursor.getTimeInMillis() != endInstant);  
  return presumedDays;  
}
于 2012-01-18T15:44:52.383 回答
16

java.time

在 Java 8 及更高版本中,使用java.time 框架教程)。

Duration

该类Duration将时间跨度表示为秒数加上小数秒。它可以计算天数、小时数、分钟数和秒数。

ZonedDateTime now = ZonedDateTime.now();
ZonedDateTime oldDate = now.minusDays(1).minusMinutes(10);
Duration duration = Duration.between(oldDate, now);
System.out.println(duration.toDays());

ChronoUnit

如果您只需要天数,您也可以使用enum。请注意,计算方法返回 a而不是。ChronoUnit longint

long days = ChronoUnit.DAYS.between( then, now );
于 2014-04-20T16:45:52.247 回答
13
import java.util.Calendar;
import java.util.Date;

public class Main {
    public static long calculateDays(String startDate, String endDate)
    {
        Date sDate = new Date(startDate);
        Date eDate = new Date(endDate);
        Calendar cal3 = Calendar.getInstance();
        cal3.setTime(sDate);
        Calendar cal4 = Calendar.getInstance();
        cal4.setTime(eDate);
        return daysBetween(cal3, cal4);
    }

    public static void main(String[] args) {
        System.out.println(calculateDays("2012/03/31", "2012/06/17"));

    }

    /** Using Calendar - THE CORRECT WAY**/
    public static long daysBetween(Calendar startDate, Calendar endDate) {
        Calendar date = (Calendar) startDate.clone();
        long daysBetween = 0;
        while (date.before(endDate)) {
            date.add(Calendar.DAY_OF_MONTH, 1);
            daysBetween++;
        }
        return daysBetween;
    }
}
于 2012-09-13T03:46:21.253 回答
12

这取决于您定义的差异。要在午夜比较两个日期,您可以这样做。

long day1 = ...; // in milliseconds.
long day2 = ...; // in milliseconds.
long days = (day2 - day1) / 86400000;
于 2010-07-29T19:10:07.243 回答
9

使用毫秒时间差的解决方案,对 DST 日期进行正确舍入:

public static long daysDiff(Date from, Date to) {
    return daysDiff(from.getTime(), to.getTime());
}

public static long daysDiff(long from, long to) {
    return Math.round( (to - from) / 86400000D ); // 1000 * 60 * 60 * 24
}

注意:当然,日期必须在某个时区。

重要代码:

Math.round( (to - from) / 86400000D )

如果你不想要圆形,你可以使用 UTC 日期,

于 2013-03-02T07:48:47.220 回答
4

问题说明:(我的代码在几周内计算增量,但同样的问题适用于几天内的增量)

这是一个看起来非常合理的实现:

public static final long MILLIS_PER_WEEK = 7L * 24L * 60L * 60L * 1000L;

static public int getDeltaInWeeks(Date latterDate, Date earlierDate) {
    long deltaInMillis = latterDate.getTime() - earlierDate.getTime();
    int deltaInWeeks = (int)(deltaInMillis / MILLIS_PER_WEEK);
    return deltaInWeeks; 
}

但是这个测试会失败:

public void testGetDeltaInWeeks() {
    delta = AggregatedData.getDeltaInWeeks(dateMar09, dateFeb23);
    assertEquals("weeks between Feb23 and Mar09", 2, delta);
}

原因是:

2009年3月9日00:00:00 EDT 2009 = 1,236,571,200,000
2月23日2月23日00:00:00 EST 2009 = 1,235,365,200,000
Millisperweek = 604,800,000

(Mar09 - 2月)/ MillisperWeek =
1,206,000,000 / 604,800,000 = 1.90,000 / 604,800,000 = 1.90

但任何看日历的人都会同意答案是 2。

于 2011-06-27T22:20:31.763 回答
3

我使用这个功能:

DATEDIFF("31/01/2016", "01/03/2016") // me return 30 days

我的功能:

import java.util.Date;

public long DATEDIFF(String date1, String date2) {
        long MILLISECS_PER_DAY = 24 * 60 * 60 * 1000;
        long days = 0l;
        SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy"); // "dd/MM/yyyy HH:mm:ss");

        Date dateIni = null;
        Date dateFin = null;        
        try {       
            dateIni = (Date) format.parse(date1);
            dateFin = (Date) format.parse(date2);
            days = (dateFin.getTime() - dateIni.getTime())/MILLISECS_PER_DAY;                        
        } catch (Exception e) {  e.printStackTrace();  }   

        return days; 
     }
于 2013-05-24T18:09:10.953 回答
2

查看这个 apache commons-lang class中的getFragmentInDaysDateUtils方法。

于 2011-08-18T15:34:05.197 回答
2

根据@Mad_Troll 的回答,我开发了这种方法。

我已经针对它运行了大约 30 个测试用例,这是正确处理次日时间片段的唯一方法。

示例:如果您通过 now & now + 1 毫秒,那仍然是同一天。正确1-1-13 23:59:59.098返回1-1-13 23:59:59.0990 天;此处发布的所有其他方法都无法正确执行此操作。

值得注意的是,它并不关心您以哪种方式放置它们,如果您的结束日期早于您的开始日期,它将倒数。

/**
 * This is not quick but if only doing a few days backwards/forwards then it is very accurate.
 *
 * @param startDate from
 * @param endDate   to
 * @return day count between the two dates, this can be negative if startDate is after endDate
 */
public static long daysBetween(@NotNull final Calendar startDate, @NotNull final Calendar endDate) {

    //Forwards or backwards?
    final boolean forward = startDate.before(endDate);
    // Which direction are we going
    final int multiplier = forward ? 1 : -1;

    // The date we are going to move.
    final Calendar date = (Calendar) startDate.clone();

    // Result
    long daysBetween = 0;

    // Start at millis (then bump up until we go back a day)
    int fieldAccuracy = 4;
    int field;
    int dayBefore, dayAfter;
    while (forward && date.before(endDate) || !forward && endDate.before(date)) {
        // We start moving slowly if no change then we decrease accuracy.
        switch (fieldAccuracy) {
            case 4:
                field = Calendar.MILLISECOND;
                break;
            case 3:
                field = Calendar.SECOND;
                break;
            case 2:
                field = Calendar.MINUTE;
                break;
            case 1:
                field = Calendar.HOUR_OF_DAY;
                break;
            default:
            case 0:
                field = Calendar.DAY_OF_MONTH;
                break;
        }
        // Get the day before we move the time, Change, then get the day after.
        dayBefore = date.get(Calendar.DAY_OF_MONTH);
        date.add(field, multiplier);
        dayAfter = date.get(Calendar.DAY_OF_MONTH);

        // This shifts lining up the dates, one field at a time.
        if (dayBefore == dayAfter && date.get(field) == endDate.get(field))
            fieldAccuracy--;
        // If day has changed after moving at any accuracy level we bump the day counter.
        if (dayBefore != dayAfter) {
            daysBetween += multiplier;
        }
    }
    return daysBetween;
}

您可以删除@NotNull注释,Intellij 使用这些注释进行动态代码分析

于 2013-10-15T11:27:42.853 回答
1

您说它“在独立程序中运行良好”,但是当您“将其包含在我的逻辑中以从报告中读取”时,您会得到“不寻常的差异值”。这表明您的报告有一些无法正常工作的值,而您的独立程序没有这些值。我建议使用测试用例,而不是独立程序。像编写独立程序一样编写测试用例,继承自 JUnit 的 TestCase 类。现在您可以运行一个非常具体的示例,知道您期望什么值(并且不要在今天给出它作为测试值,因为今天会随着时间而变化)。如果您输入您在独立程序中使用的值,您的测试可能会通过。太好了 - 您希望这些案例继续有效。现在,从您的报告中添加一个值,一个没有 工作不正常。您的新测试可能会失败。找出它失败的原因,修复它,然后变成绿色(所有测试都通过)。运行您的报告。看看还有什么坏的;写一个测试;让它通过。很快你就会发现你的报告是有效的。

于 2010-07-21T14:03:58.040 回答
1

这个基本功能几百行代码???

只是一个简单的方法:

protected static int calculateDayDifference(Date dateAfter, Date dateBefore){
    return (int)(dateAfter.getTime()-dateBefore.getTime())/(1000 * 60 * 60 * 24); 
    // MILLIS_IN_DAY = 1000 * 60 * 60 * 24;
}
于 2014-08-12T09:43:14.693 回答
1
public static int getDifferenceIndays(long timestamp1, long timestamp2) {
    final int SECONDS = 60;
    final int MINUTES = 60;
    final int HOURS = 24;
    final int MILLIES = 1000;
    long temp;
    if (timestamp1 < timestamp2) {
        temp = timestamp1;
        timestamp1 = timestamp2;
        timestamp2 = temp;
    }
    Calendar startDate = Calendar.getInstance(TimeZone.getDefault());
    Calendar endDate = Calendar.getInstance(TimeZone.getDefault());
    endDate.setTimeInMillis(timestamp1);
    startDate.setTimeInMillis(timestamp2);
    if ((timestamp1 - timestamp2) < 1 * HOURS * MINUTES * SECONDS * MILLIES) {
        int day1 = endDate.get(Calendar.DAY_OF_MONTH);
        int day2 = startDate.get(Calendar.DAY_OF_MONTH);
        if (day1 == day2) {
            return 0;
        } else {
            return 1;
        }
    }
    int diffDays = 0;
    startDate.add(Calendar.DAY_OF_MONTH, diffDays);
    while (startDate.before(endDate)) {
        startDate.add(Calendar.DAY_OF_MONTH, 1);
        diffDays++;
    }
    return diffDays;
}
于 2014-12-24T17:34:57.200 回答
1

三十-额外

Vitalii Fedorenko的答案是正确的,描述了如何使用Java 8 及更高版本中内置的java.time类 ( Duration& )以现代方式执行此计算(并向后移植到 Java 6 & 7Android)。ChronoUnit

Days

如果您在代码中经常使用天数,则可以使用类替换单纯的整数。该类Days可以在ThreeTen-Extra项目中找到,该项目是 java.time 的扩展,也是 java.time 未来可能添加的试验场。该类Days提供了一种类型安全的方式来表示应用程序中的天数。该类包括方便的常量ZEROONE

鉴于java.util.Date问题中的旧过时对象,首先将它们转换为现代java.time.Instant对象。旧的日期时间类有新添加的方法来促进转换为 java.time,例如java.util.Date::toInstant.

Instant start = utilDateStart.toInstant(); // Inclusive.
Instant stop = utilDateStop.toInstant();  // Exclusive.

将这两个Instant对象传递给工厂方法org.threeten.extra.Days

在当前的实现(2016-06)中,这是一个包装器调用java.time.temporal.ChronoUnit.DAYS.between,请阅读ChronoUnit类文档了解详细信息。需要明确的是:所有大写字母DAYS都在枚举中ChronoUnit,而 initial-capDays是 ThreeTen-Extra 中的一个类。

Days days = Days.between( start , stop );

Days您可以在自己的代码中传递这些对象。您可以通过调用将序列化为标准ISO 8601toString格式的字符串。这种格式PnD使用 aP来标记开始,D意思是“天”,中间有天数。java.time 类和 ThreeTen-Extra 在生成和解析表示日期时间值的字符串时默认使用这些标准格式。

String output = days.toString();

P3D

Days days = Days.parse( "P3D" );  
于 2016-06-14T19:44:00.530 回答
0

此代码计算 2 个日期字符串之间的天数:

    static final long MILLI_SECONDS_IN_A_DAY = 1000 * 60 * 60 * 24;
    static final String DATE_FORMAT = "dd-MM-yyyy";
    public long daysBetween(String fromDateStr, String toDateStr) throws ParseException {
    SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
    Date fromDate;
    Date toDate;
    fromDate = format.parse(fromDateStr);
    toDate = format.parse(toDateStr);
    return (toDate.getTime() - fromDate.getTime()) / MILLI_SECONDS_IN_A_DAY;
}
于 2014-08-16T09:45:46.153 回答
0

如果您正在寻找一个解决方案,它可以在 eg11/30/2014 23:5912/01/2014 00:01这里使用 Joda Time 的解决方案之间返回正确的数字或​​天数。

private int getDayDifference(long past, long current) {
    DateTime currentDate = new DateTime(current);
    DateTime pastDate = new DateTime(past);
    return currentDate.getDayOfYear() - pastDate.getDayOfYear();
} 

此实现将以1天数的形式返回。此处发布的大多数解决方案都以毫秒为单位计算两个日期之间的差异。这意味着这0将被返回,因为这两个日期之间只有 2 分钟的差异。

于 2014-12-03T16:02:06.730 回答
0

您应该使用 Joda Time 库,因为 Java Util Date 有时会返回错误的值。

Joda vs Java Util Date

例如昨天 (dd-mm-yyyy, 12-07-2016) 和 1957 年第一天 (dd-mm-yyyy, 01-01-1957) 之间的日子:

public class Main {

public static void main(String[] args) {
    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");

    Date date = null;
    try {
        date = format.parse("12-07-2016");
    } catch (ParseException e) {
        e.printStackTrace();
    }

    //Try with Joda - prints 21742
    System.out.println("This is correct: " + getDaysBetweenDatesWithJodaFromYear1957(date));
    //Try with Java util - prints 21741
    System.out.println("This is not correct: " + getDaysBetweenDatesWithJavaUtilFromYear1957(date));    
}


private static int getDaysBetweenDatesWithJodaFromYear1957(Date date) {
    DateTime jodaDateTime = new DateTime(date);
    DateTimeFormatter formatter = DateTimeFormat.forPattern("dd-MM-yyyy");
    DateTime y1957 = formatter.parseDateTime("01-01-1957");

    return Days.daysBetween(y1957 , jodaDateTime).getDays();
}

private static long getDaysBetweenDatesWithJavaUtilFromYear1957(Date date) {
    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");

    Date y1957 = null;
    try {
        y1957 = format.parse("01-01-1957");
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return TimeUnit.DAYS.convert(date.getTime() - y1957.getTime(), TimeUnit.MILLISECONDS);
}

所以我真的建议你使用 Joda Time 库。

于 2016-07-13T19:30:02.393 回答
-6

我是这样做的。这简单 :)

Date d1 = jDateChooserFrom.getDate();
Date d2 = jDateChooserTo.getDate();

Calendar day1 = Calendar.getInstance();
day1.setTime(d1);

Calendar day2 = Calendar.getInstance();
day2.setTime(d2);

int from = day1.get(Calendar.DAY_OF_YEAR);
int to = day2.get(Calendar.DAY_OF_YEAR);

int difference = to-from;
于 2013-10-08T03:28:18.683 回答