web-dev-qa-db-ja.com

Android / Java-日付の日数の違い

私は次のコードを使用して現在の日付(1999年12月31日形式、すなわちmm/dd/yyyy)を取得しています:

Textview txtViewData;
txtViewDate.setText("Today is " +
        Android.text.format.DateFormat.getDateFormat(this).format(new Date()));

そして、私は次の形式の別の日付を持っています:2010-08-25(つまりyyyy/mm/dd)、

だから私は日数の日付の違いを見つけたいのですが、どのように日数の違いを見つけるのですか?

(言い換えれば、CURRENT DATE-yyyy/mm/dd format date)の違いを見つけたい

75
Paresh Mayani

実際には信頼できる方法ではなく、 JodaTime を使用する方が良い

  Calendar thatDay = Calendar.getInstance();
  thatDay.set(Calendar.DAY_OF_MONTH,25);
  thatDay.set(Calendar.MONTH,7); // 0-11 so 1 less
  thatDay.set(Calendar.YEAR, 1985);

  Calendar today = Calendar.getInstance();

  long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis

近似値は次のとおりです...

long days = diff / (24 * 60 * 60 * 1000);

文字列から日付を解析するには、使用できます

  String strThatDay = "1985/08/25";
  SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
  Date d = null;
  try {
   d = formatter.parse(strThatDay);//catch exception
  } catch (ParseException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } 


  Calendar thatDay = Calendar.getInstance();
  thatDay.setTime(d); //rest is the same....

ただし、日付形式は確実であるため...数値を取得するために、そのサブストリングに対してInteger.parseInt()を実行することもできます。

123
st0le

これは私の仕事ではありません、答えを見つけました here 。将来的にリンク切れを望んでいませんでした:)。

重要なのは、夏時間の設定を考慮に入れるためのこの行です。フルコードを参照してください。

TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));

または、TimeZoneをパラメーターとしてdaysBetween()に渡し、sDateおよびeDateオブジェクトでsetTimeZone()を呼び出してみてください。

だからここに行く:

public static Calendar getDatePart(Date date){
    Calendar cal = Calendar.getInstance();       // get calendar instance
    cal.setTime(date);      
    cal.set(Calendar.HOUR_OF_DAY, 0);            // set hour to midnight
    cal.set(Calendar.MINUTE, 0);                 // set minute in hour
    cal.set(Calendar.SECOND, 0);                 // set second in minute
    cal.set(Calendar.MILLISECOND, 0);            // set millisecond in second

    return cal;                                  // return the date part
}

here から取得したgetDatePart()

/**
 * This method also assumes endDate >= startDate
**/
public static long daysBetween(Date startDate, Date endDate) {
  Calendar sDate = getDatePart(startDate);
  Calendar eDate = getDatePart(endDate);

  long daysBetween = 0;
  while (sDate.before(eDate)) {
      sDate.add(Calendar.DAY_OF_MONTH, 1);
      daysBetween++;
  }
  return daysBetween;
}

ニュアンス:2つの日付の差を見つけることは、2つの日付を減算し、結果を(24 * 60 * 60 * 1000で除算するほど簡単ではありません)。事実、その誤りです!

例:2つの日付03/24/2007と03/25/2007の差は1日です。ただし、上記の方法を使用すると、英国では0日を取得できます!

ご自身でご覧ください(以下のコード)。ミリ秒単位で進むとエラーが四捨五入され、夏時間のような小さなものが出てきたら、それらは最も明白になります。

完全なコード:

import Java.text.SimpleDateFormat;
import Java.util.Calendar;
import Java.util.Date;
import Java.util.TimeZone;

public class DateTest {

public class DateTest {

static SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");

public static void main(String[] args) {

  TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));

  //diff between these 2 dates should be 1
  Date d1 = new Date("01/01/2007 12:00:00");
  Date d2 = new Date("01/02/2007 12:00:00");

  //diff between these 2 dates should be 1
  Date d3 = new Date("03/24/2007 12:00:00");
  Date d4 = new Date("03/25/2007 12:00:00");

  Calendar cal1 = Calendar.getInstance();cal1.setTime(d1);
  Calendar cal2 = Calendar.getInstance();cal2.setTime(d2);
  Calendar cal3 = Calendar.getInstance();cal3.setTime(d3);
  Calendar cal4 = Calendar.getInstance();cal4.setTime(d4);

  printOutput("Manual   ", d1, d2, calculateDays(d1, d2));
  printOutput("Calendar ", d1, d2, daysBetween(cal1, cal2));
  System.out.println("---");
  printOutput("Manual   ", d3, d4, calculateDays(d3, d4));
  printOutput("Calendar ", d3, d4, daysBetween(cal3, cal4));
}


private static void printOutput(String type, Date d1, Date d2, long result) {
  System.out.println(type+ "- Days between: " + sdf.format(d1)
                    + " and " + sdf.format(d2) + " is: " + result);
}

/** Manual Method - YIELDS INCORRECT RESULTS - DO NOT USE**/
/* This method is used to find the no of days between the given dates */
public static long calculateDays(Date dateEarly, Date dateLater) {
  return (dateLater.getTime() - dateEarly.getTime()) / (24 * 60 * 60 * 1000);
}

/** Using Calendar - THE CORRECT WAY**/
public static long daysBetween(Date startDate, Date endDate) {
  ...
}

出力:

マニュアル-2007年1月1日から2007年1月2日までの日数:1

カレンダー-2007年1月1日から2007年1月2日までの日数:1


手動-2007年3月24日から2007年3月25日までの日数は0

カレンダー-2007年3月24日から2007年3月25日までの日数:1

80
Samuel

ほとんどの答えは、あなたの問題によく合っていました。

だから私は日数の日付の違いを見つけたいのですが、どのように日数の違いを見つけるのですか?

どのタイムゾーンでも正しい違いが得られることが保証されている、この非常にシンプルでわかりやすいアプローチをお勧めします。

int difference= 
((int)((startDate.getTime()/(24*60*60*1000))
-(int)(endDate.getTime()/(24*60*60*1000))));

以上です!

36
Lisa Anne

jodatime API を使用します

Days.daysBetween(start.toDateMidnight() , end.toDateMidnight() ).getDays() 

ここで、「開始」と「終了」は DateTime オブジェクトです。日付文字列をDateTimeオブジェクトに解析するには、 parseDateTimeメソッド を使用します

Android固有のJodaTimeライブラリ もあります。

24

このフラグメントは夏時間の原因であり、O(1)です。

private final static long MILLISECS_PER_DAY = 24 * 60 * 60 * 1000;

private static long getDateToLong(Date date) {
    return Date.UTC(date.getYear(), date.getMonth(), date.getDate(), 0, 0, 0);
}

public static int getSignedDiffInDays(Date beginDate, Date endDate) {
    long beginMS = getDateToLong(beginDate);
    long endMS = getDateToLong(endDate);
    long diff = (endMS - beginMS) / (MILLISECS_PER_DAY);
    return (int)diff;
}

public static int getUnsignedDiffInDays(Date beginDate, Date endDate) {
    return Math.abs(getSignedDiffInDays(beginDate, endDate));
}
14
markshiz

これは私にとってシンプルで最適な計算であり、あなたのためかもしれません。

       try {
            /// String CurrDate=  "10/6/2013";
            /// String PrvvDate=  "10/7/2013";
            Date date1 = null;
            Date date2 = null;
            SimpleDateFormat df = new SimpleDateFormat("M/dd/yyyy");
            date1 = df.parse(CurrDate);
            date2 = df.parse(PrvvDate);
            long diff = Math.abs(date1.getTime() - date2.getTime());
            long diffDays = diff / (24 * 60 * 60 * 1000);


            System.out.println(diffDays);

        } catch (Exception e1) {
            System.out.println("exception " + e1);
        }
6
Rishi Gautam

これを行うための最良かつ最も簡単な方法

  public int getDays(String begin) throws ParseException {
     long MILLIS_PER_DAY = 24 * 60 * 60 * 1000;
     SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);

    long begin = dateFormat.parse(begin).getTime();
    long end = new Date().getTime(); // 2nd date want to compare
    long diff = (end - begin) / (MILLIS_PER_DAY);
    return (int) diff;
}
3
Sumit

tl; dr

ChronoUnit.DAYS.between( 
    LocalDate.parse( "1999-12-28" ) , 
    LocalDate.parse( "12/31/1999" , DateTimeFormatter.ofPattern( "MM/dd/yyyy" ) ) 
)

詳細

他の答えは時代遅れです。最も古いバージョンのJavaにバンドルされている古い日時クラスは、設計が不十分で、混乱し、面倒であることが証明されています。それらを避けてください。

Java.time

Joda-Timeプロジェクトは、これらの古いクラスの代替として非常に成功しました。これらのクラスは、Java 8以降に組み込まれた Java.time フレームワークのインスピレーションを提供しました。

Java.time機能の多くは、 ThreeTen-Backport のJava 6および7にバックポートされ、さらに ThreeTenABP のAndroidに適合します。

LocalDate

LocalDate クラスは、時刻とタイムゾーンのない日付のみの値を表します。

文字列の解析

入力文字列が標準の ISO 8601 形式の場合、LocalDateクラスは文字列を直接解析できます。

LocalDate start = LocalDate.parse( "1999-12-28" );

ISO 8601形式でない場合は、DateTimeFormatterでフォーマットパターンを定義します。

String input = "12/31/1999";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "MM/dd/yyyy" );
LocalDate stop = LocalDate.parse( input , formatter );

ChronoUnitによる経過日数

ここで、そのLocalDateオブジェクトのペア間の経過日数を取得します。 ChronoUnit 列挙型は経過時間を計算します。

long totalDays = ChronoUnit.DAYS.between( start , stop ) ; 

Java列挙型に慣れていない場合は、他のほとんどのプログラミング言語の従来の列挙型よりもはるかに強力で便利であることを理解してください。詳細については、 Enum クラスのドキュメント、 Oracleチュートリアル 、および Wikipedia を参照してください。


Java.timeについて

Java.time フレームワークは、Java 8以降に組み込まれています。これらのクラスは、 Java.util.DateCalendar 、および SimpleDateFormat などの厄介な古い レガシー 日時クラスに取って代わります。

Joda-Time プロジェクトは、現在 メンテナンスモード であり、 Java.time クラスへの移行を推奨しています。

詳細については、 Oracleチュートリアル を参照してください。また、Stack Overflowで多くの例と説明を検索してください。仕様は JSR 31 です。

Java.timeクラスはどこで入手できますか?

  • Java SE 8 および SE 9 以降
    • ビルトイン。
    • 実装がバンドルされた標準Java AP​​Iの一部。
    • Java 9は、いくつかのマイナーな機能と修正を追加します。
  • Java SE 6 および SE 7
    • Java.timeの機能の多くは、 ThreeTen-Backport のJava 6および7にバックポートされています。 。
  • Android

ThreeTen-Extra プロジェクトは、クラスを追加してJava.timeを拡張します。このプロジェクトは、Java.timeに将来追加される可能性のある証明の場です。 IntervalYearWeekYearQuartermore などの便利なクラスがあります。

3
Basil Bourque

Sam Questの回答のCorrect Wayは、最初の日付が2番目の日付よりも早い場合にのみ機能します。さらに、2つの日付が1日以内であれば1を返します。

これが私にとって最適なソリューションです。他のほとんどのソリューションと同様に、夏時間のオフセットが間違っているため、1年の2日間で誤った結果が表示されます。

private final static long MILLISECS_PER_DAY = 24 * 60 * 60 * 1000;

long calculateDeltaInDays(Calendar a, Calendar b) {

    // Optional: avoid cloning objects if it is the same day
    if(a.get(Calendar.ERA) == b.get(Calendar.ERA) 
            && a.get(Calendar.YEAR) == b.get(Calendar.YEAR)
            && a.get(Calendar.DAY_OF_YEAR) == b.get(Calendar.DAY_OF_YEAR)) {
        return 0;
    }
    Calendar a2 = (Calendar) a.clone();
    Calendar b2 = (Calendar) b.clone();
    a2.set(Calendar.HOUR_OF_DAY, 0);
    a2.set(Calendar.MINUTE, 0);
    a2.set(Calendar.SECOND, 0);
    a2.set(Calendar.MILLISECOND, 0);
    b2.set(Calendar.HOUR_OF_DAY, 0);
    b2.set(Calendar.MINUTE, 0);
    b2.set(Calendar.SECOND, 0);
    b2.set(Calendar.MILLISECOND, 0);
    long diff = a2.getTimeInMillis() - b2.getTimeInMillis();
    long days = diff / MILLISECS_PER_DAY;
    return Math.abs(days);
}
3
ccpizza

これらのソリューションはすべて、2つの問題のいずれかに悩まされています。丸め誤差、うるう日、秒などのために解決策が完全に正確ではないか、2つの未知の日付の間の日数にわたってループすることになります。

この解決策は最初の問題を解決し、2番目の問題を約365倍改善します。最大範囲がわかっている場合はより良いです。

/**
 * @param thisDate
 * @param thatDate
 * @param maxDays
 *            set to -1 to not set a max
 * @returns number of days covered between thisDate and thatDate, inclusive, i.e., counting both
 *          thisDate and thatDate as an entire day. Will short out if the number of days exceeds
 *          or meets maxDays
 */
public static int daysCoveredByDates(Date thisDate, Date thatDate, int maxDays) {
    //Check inputs
    if (thisDate == null || thatDate == null) {
        return -1;
    }

    //Set calendar objects
    Calendar startCal = Calendar.getInstance();
    Calendar endCal = Calendar.getInstance();
    if (thisDate.before(thatDate)) {
        startCal.setTime(thisDate);
        endCal.setTime(thatDate);
    }
    else {
        startCal.setTime(thatDate);
        endCal.setTime(thisDate);
    }

    //Get years and dates of our times.
    int startYear = startCal.get(Calendar.YEAR);
    int endYear = endCal.get(Calendar.YEAR);
    int startDay = startCal.get(Calendar.DAY_OF_YEAR);
    int endDay = endCal.get(Calendar.DAY_OF_YEAR);

    //Calculate the number of days between dates.  Add up each year going by until we catch up to endDate.
    while (startYear < endYear && maxDays >= 0 && endDay - startDay + 1 < maxDays) {
        endDay += startCal.getActualMaximum(Calendar.DAY_OF_YEAR); //adds the number of days in the year startDate is currently in
        ++startYear;
        startCal.set(Calendar.YEAR, startYear); //reup the year
    }
    int days = endDay - startDay + 1;

    //Honor the maximum, if set
    if (maxDays >= 0) {
        days = Math.min(days, maxDays);
    }
    return days;
}

日付間の日付(後者の日付を含まない)が必要な場合は、+ 1が表示されたらendDay - startDay + 1を削除してください。

2
drdaanger

次の機能を使用します。

   /**
     * Returns the number of days between two dates. The time part of the
     * days is ignored in this calculation, so 2007-01-01 13:00 and 2007-01-02 05:00
     * have one day inbetween.
     */
    public static long daysBetween(Date firstDate, Date secondDate) {
        // We only use the date part of the given dates
        long firstSeconds = truncateToDate(firstDate).getTime()/1000;
        long secondSeconds = truncateToDate(secondDate).getTime()/1000;
        // Just taking the difference of the millis.
        // These will not be exactly multiples of 24*60*60, since there
        // might be daylight saving time somewhere inbetween. However, we can
        // say that by adding a half day and rounding down afterwards, we always
        // get the full days.
        long difference = secondSeconds-firstSeconds;
        // Adding half a day
        if( difference >= 0 ) {
            difference += SECONDS_PER_DAY/2; // plus half a day in seconds
        } else {
            difference -= SECONDS_PER_DAY/2; // minus half a day in seconds
        }
        // Rounding down to days
        difference /= SECONDS_PER_DAY;

        return difference;
    }

    /**
     * Truncates a date to the date part alone.
     */
    @SuppressWarnings("deprecation")
    public static Date truncateToDate(Date d) {
        if( d instanceof Java.sql.Date ) {
            return d; // Java.sql.Date is already truncated to date. And raises an
                      // Exception if we try to set hours, minutes or seconds.
        }
        d = (Date)d.clone();
        d.setHours(0);
        d.setMinutes(0);
        d.setSeconds(0);
        d.setTime(((d.getTime()/1000)*1000));
        return d;
    }
2
Daniel

少なくとも私にとっては、実行可能な唯一の解決策である単純な解決策があります。

問題は、Joda、Calendar、Date、その他を使用して、私が見ているすべての答えが、ミリ秒の量しか考慮しないことです。最終的には、実際の日数ではなく、2つの日付の間の24時間サイクルの数をカウントします。したがって、1月1日の午後11時から1月2日の午前1時までは、0日を返します。

startDateからendDateまでの実際の日数を数えるには、次のようにします。

// Find the sequential day from a date, essentially resetting time to start of the day
long startDay = startDate.getTime() / 1000 / 60 / 60 / 24;
long endDay = endDate.getTime() / 1000 / 60 / 60 / 24;

// Find the difference, duh
long daysBetween = endDay - startDay;

これは、1月2日から1月1日までの間に「1」を返します。終了日をカウントする必要がある場合は、daysBetweenに1を追加するだけです(範囲内の合計日数をカウントするため、コードでこれを行う必要がありました)。

これは Danielが示唆した に似ていますが、より小さいコードだと思います。

2
zeh

別の方法:

public static int numberOfDaysBetweenDates(Calendar fromDay, Calendar toDay) {
        fromDay = calendarStartOfDay(fromDay);
        toDay = calendarStartOfDay(toDay);
        long from = fromDay.getTimeInMillis();
        long to = toDay.getTimeInMillis();
        return (int) TimeUnit.MILLISECONDS.toDays(to - from);
    }
1
anil

これを行うための非常に簡単な方法を見つけたので、アプリで使用しています。

Timeオブジェクトに日付があるとしましょう(または、ミリ秒だけが必要です)。

Time date1 = initializeDate1(); //get the date from somewhere
Time date2 = initializeDate2(); //get the date from somewhere

long millis1 = date1.toMillis(true);
long millis2 = date2.toMillis(true);

long difference = millis2 - millis1 ;

//now get the days from the difference and that's it
long days = TimeUnit.MILLISECONDS.toDays(difference);

//now you can do something like
if(days == 7)
{
    //do whatever when there's a week of difference
}

if(days >= 30)
{
    //do whatever when it's been a month or more
}
0
Gonan
        Date userDob = new SimpleDateFormat("yyyy-MM-dd").parse(dob);
        Date today = new Date();
        long diff =  today.getTime() - userDob.getTime();
        int numOfDays = (int) (diff / (1000 * 60 * 60 * 24));
        int hours = (int) (diff / (1000 * 60 * 60));
        int minutes = (int) (diff / (1000 * 60));
        int seconds = (int) (diff / (1000));
0
Nilesh Savaliya

ジョーダタイム

最善の方法は、プロジェクトに追加する非常に成功したオープンソースライブラリである Joda-Time を使用することです。

String date1 = "2015-11-11";
String date2 = "2013-11-11";
DateTimeFormatter formatter = new DateTimeFormat.forPattern("yyyy-MM-dd");
DateTime d1 = formatter.parseDateTime(date1);
DateTime d2 = formatter.parseDateTime(date2);
long diffInMillis = d2.getMillis() - d1.getMillis();

Duration duration = new Duration(d1, d2);
int days = duration.getStandardDays();
int hours = duration.getStandardHours();
int minutes = duration.getStandardMinutes();

Android Studio を使用している場合、joda-timeの追加は非常に簡単です。 build.gradle(アプリ)で:

dependencies {
  compile 'joda-time:joda-time:2.4'
  compile 'joda-time:joda-time:2.4'
  compile 'joda-time:joda-time:2.2'
}
0
Kristy Welsh
        public void dateDifferenceExample() {

        // Set the date for both of the calendar instance
        GregorianCalendar calDate = new GregorianCalendar(2012, 10, 02,5,23,43);
        GregorianCalendar cal2 = new GregorianCalendar(2015, 04, 02);

        // Get the represented date in milliseconds
        long millis1 = calDate.getTimeInMillis();
        long millis2 = cal2.getTimeInMillis();

        // Calculate difference in milliseconds
        long diff = millis2 - millis1;

        // Calculate difference in seconds
        long diffSeconds = diff / 1000;

        // Calculate difference in minutes
        long diffMinutes = diff / (60 * 1000);

        // Calculate difference in hours
        long diffHours = diff / (60 * 60 * 1000);

        // Calculate difference in days
        long diffDays = diff / (24 * 60 * 60 * 1000);
    Toast.makeText(getContext(), ""+diffSeconds, Toast.LENGTH_SHORT).show();


}
0

これらの機能を使用する

    public static int getDateDifference(int previousYear, int previousMonthOfYear, int previousDayOfMonth, int nextYear, int nextMonthOfYear, int nextDayOfMonth, int differenceToCount){
    // int differenceToCount = can be any of the following
    //  Calendar.MILLISECOND;
    //  Calendar.SECOND;
    //  Calendar.MINUTE;
    //  Calendar.HOUR;
    //  Calendar.DAY_OF_MONTH;
    //  Calendar.MONTH;
    //  Calendar.YEAR;
    //  Calendar.----

    Calendar previousDate = Calendar.getInstance();
    previousDate.set(Calendar.DAY_OF_MONTH, previousDayOfMonth);
    // month is zero indexed so month should be minus 1
    previousDate.set(Calendar.MONTH, previousMonthOfYear);
    previousDate.set(Calendar.YEAR, previousYear);

    Calendar nextDate = Calendar.getInstance();
    nextDate.set(Calendar.DAY_OF_MONTH, previousDayOfMonth);
    // month is zero indexed so month should be minus 1
    nextDate.set(Calendar.MONTH, previousMonthOfYear);
    nextDate.set(Calendar.YEAR, previousYear);

    return getDateDifference(previousDate,nextDate,differenceToCount);
}
public static int getDateDifference(Calendar previousDate,Calendar nextDate,int differenceToCount){
    // int differenceToCount = can be any of the following
    //  Calendar.MILLISECOND;
    //  Calendar.SECOND;
    //  Calendar.MINUTE;
    //  Calendar.HOUR;
    //  Calendar.DAY_OF_MONTH;
    //  Calendar.MONTH;
    //  Calendar.YEAR;
    //  Calendar.----

    //raise an exception if previous is greater than nextdate.
    if(previousDate.compareTo(nextDate)>0){
        throw new RuntimeException("Previous Date is later than Nextdate");
    }

    int difference=0;
    while(previousDate.compareTo(nextDate)<=0){
        difference++;
        previousDate.add(differenceToCount,1);
    }
    return difference;
}
0
neal zedlav