81

2つの日付の間の日数を見つける必要があります。1つはレポートからのもので、もう1つは現在の日付です。私のスニペット:

  int age=calculateDifference(agingDate, today);

これcalculateDifferenceはプライベートメソッドでagingDateあり、明確にするためtodayDateオブジェクトです。私はJavaフォーラムの2つの記事、スレッド1 /スレッド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

欠陥のある java.util.Date などの代わりに、優れたJoda Timeライブラリを使用することをお勧めします。あなたは単に書くことができます

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 * など) はタイムゾーンを考慮していないため、デフォルトのタイムゾーンに 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を使用できます。計算メソッドがではなく を返すことに注意してください。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

それはあなたが違いとして何を定義するかに依存します。真夜中の2つの日付を比較するには、次のことができます。

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
}

1 つの注意: もちろん、日付は何らかのタイムゾーンにある必要があります。

重要なコード:

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);
}

その理由は:

Mon Mar 09 00:00:00 EDT 2009 = 1,236,571,200,000
Mon Feb 23 00:00:00 EST 2009 = 1,235,365,200,000
MillisPerWeek = 604,800,000
したがって、
(Mar09-2月23日)/ MillisPerWeek =
1,206,000,000 / 604,800,000 = 1.994 .. ..

しかし、カレンダーを見ている人なら誰でも、答えは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

@ Mad_Troll の回答に基づいて、このメソッドを開発しました。

私はそれに対して約 30 のテスト ケースを実行しましたが、サブ デイ タイム フラグメントを正しく処理する唯一の方法です。

例: now & now + 1 ミリ秒を渡すと、まだ同じ日です。正しく0 日1-1-13 23:59:59.098を返します。1-1-13 23:59:59.099ここに掲載されている他の方法の割り当ては、これを正しく行いません。

終了日が開始日より前の場合は、逆にカウントされます。

/**
 * 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 に答える
2

この apache commons-lang classのgetFragmentInDaysメソッドを見てくださいDateUtils

于 2011-08-18T15:34:05.197 に答える
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

スリーテンエクストラ

Vitalii Fedorenko による回答は正しく、 Java 8 以降に組み込まれたjava.timeクラス ( Duration& ) (および Java 6 & 7およびAndroidにバックポートされた)を使用して、この計算を最新の方法で実行する方法を説明しています。ChronoUnit

Days

コードで日常的に日数を使用している場合は、単なる整数をクラスの使用に置き換えることができます。このDaysクラスは、ThreeTen-Extraプロジェクトで見つけることができます。これは、java.time の拡張であり、java.time への将来の追加の可能性を証明する基盤です。このDaysクラスは、アプリケーションで日数を表すタイプ セーフな方法を提供します。ZEROこのクラスには、およびの便利な定数が含まれていONEます。

質問の古い時代遅れ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.betweenChronoUnitクラスのドキュメントを参照してください。明確にするために: すべての大文字DAYSは enumChronoUnitにあり、initial-capDaysは ThreeTen-Extra のクラスです。

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

Daysこれらのオブジェクトを独自のコードに渡すことができます。を呼び出すことにより、標準ISO 8601形式の文字列にシリアル化できますtoString。この形式のは、開始を示すために a を使用し、「日」をPnD意味し、その間に日数が入ります。java.time クラスと ThreeTen-Extra はどちらも、日時値を表す文字列を生成および解析するときに、デフォルトでこれらの標準形式を使用します。PD

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

11/30/2014 23:59たとえば、12/01/2014 00:01Joda Time を使用したソリューションとの間の適切な日数または日数を返すソリューションを探している場合。

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

この実装は1、日数の差として返されます。ここに掲載されているソリューションのほとんどは、2 つの日付の差をミリ秒単位で計算します。0これは、これら 2 つの日付の差が 2 分しかないため、 が返されることを意味します。

于 2014-12-03T16:02:06.730 に答える
0

Java Util Date は時々間違った値を返すため、Joda Time ライブラリを使用する必要があります。

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 に答える