Android/Java - 以天为单位的日期差异

Android/Java - 以天为单位的日期差异

IT小君   2021-09-15T00:20:37

我使用以下代码获取当前日期(格式为 12/31/1999 即 mm/dd/yyyy):

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

我还有另一个格式为:2010-08-25 (ie yyyy/mm/dd) 的日期,

所以我想找到日期之间的天数差异,我如何找到天数差异?

(换句话说,我想找到CURRENT DATE - yyyy/mm/dd 格式化日期之间的区别

服务器费用不足...
评论(18)
IT小君

不是一个可靠的方法,最好使用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()在它的子字符串上以获得它们的数值。

2021-09-15T00:21:01   回复
IT小君

这不是我的工作,在这里找到了答案不希望将来断开链接:)。

关键是考虑到日光设置的这一行,参考完整代码。

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

或尝试通过TimeZone 作为参数来daysBetween()和呼叫setTimeZone()sDateeDate对象。

所以这里是这样的:

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
}

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

细微差别找出两个日期之间的差异并不像减去两个日期并将结果除以 (24 * 60 * 60 * 1000) 那样简单。事实上,它是错误的!

例如: 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

2021-09-15T00:21:05   回复
IT小君

大多数答案都很好,适合您的问题

所以我想找到日期之间的天数差异,我如何找到天数差异?

我建议采用这种非常简单直接的方法,可以保证在任何时区为您提供正确的差异:

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

就是这样!

2021-09-15T00:21:06   回复
IT小君

使用jodatime API

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

其中 'start' 和 'end' 是您的DateTime对象。要将日期字符串解析为 DateTime 对象,请使用parseDateTime 方法

还有一个android 特定的 JodaTime 库

2021-09-15T00:21:06   回复
IT小君

该片段考虑了夏令时并且是 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));
}
2021-09-15T00:21:06   回复
IT小君

这对我来说是简单和最好的计算,可能也适合你。

       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);
        }
2021-09-15T00:21:06   回复
IT小君

tl;博士

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

细节

其他答案已过时。与最早版本的 Java 捆绑在一起的旧日期时间类已被证明设计不佳、混乱且麻烦。避开它们。

时间

Joda-Time 项目非常成功地替代了那些旧类。这些类 为 Java 8 及更高版本中内置java.time框架提供了灵感

多的java.time功能后移植到Java 6和7在ThreeTen-反向移植和在进一步适于到Android ThreeTenABP

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 教程维基百科以了解更多信息。


关于 java.time

java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat

现在处于维护模式Joda-Time项目建议迁移到java.time类。

要了解更多信息,请参阅Oracle 教程并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310

从哪里获得 java.time 类?

ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多

2021-09-15T00:21:07   回复
IT小君

Correct Way萨姆任务的回答只有当第一个日期比第二早期的作品。此外,如果两个日期在一天之内,它将返回 1。

这是最适合我的解决方案。就像大多数其他解决方案一样,由于错误的夏令时偏移,它仍然会在一年中的两天显示不正确的结果。

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);
}
2021-09-15T00:21:07   回复
IT小君

最好和最简单的方法来做到这一点

  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;
}
2021-09-15T00:21:08   回复
IT小君

使用以下功能:

   /**
     * 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;
    }
2021-09-15T00:21:08   回复
IT小君

有一个简单的解决方案,至少对我来说,是唯一可行的解​​决方案。

问题是我看到的所有答案都被扔了——使用 Joda、日历、日期或其他任何东西——只考虑了毫秒数。他们最终计算两个日期之间的 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”。如果您需要计算结束日期,只需将 1 添加到daysBetween(我需要在我的代码中这样做,因为我想计算范围内的总天数)。

这有点类似于Daniel 的建议,但我认为代码较小。

2021-09-15T00:21:08   回复
IT小君

所有这些解决方案都存在两个问题之一。由于舍入错误、闰日和秒数等原因,解决方案不完全准确,或者您最终会遍历两个未知日期之间的天数。

此解决方案解决了第一个问题,并将第二个问题提高了大约 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.

2021-09-15T00:21:08   回复
IT小君

另一种方式:

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);
    }
2021-09-15T00:21:09   回复
IT小君

使用这些功能

    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;
}
2021-09-15T00:21:09   回复
IT小君
        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();


}
2021-09-15T00:21:09   回复
IT小君

我找到了一种非常简单的方法来做到这一点,这就是我在我的应用程序中使用的方法。

假设您在 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
}
2021-09-15T00:21:09   回复
IT小君

乔达时间

最好的方法是使用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 (app) 中:

dependencies {
  compile 'joda-time:joda-time:2.4'
  compile 'joda-time:joda-time:2.4'
  compile 'joda-time:joda-time:2.2'
}
2021-09-15T00:21:09   回复
IT小君
        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));
2021-09-15T00:21:10   回复