【问题标题】:Android/Java - Date Difference in daysAndroid/Java - 以天为单位的日期差异
【发布时间】:2011-04-19 19:21:36
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 这段代码使用了麻烦的旧日期时间类,现在已被 java.time 类取代。对于较旧的 Java 和 Android,请参阅 ThreeTen-BackportThreeTenABP 项目。
  • 类似问题,但使用时刻而不是整个日期:date difference in days, in Android

标签: java android date


【解决方案1】:

不是一个真正可靠的方法,最好使用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() 来获取它们的数值。

【讨论】:

  • @stOle thanx ,但是我在字符串中都有日期,所以我该怎么做,请告诉我详细信息,请
  • @stOle 没有得到确切的答案,可能是您的代码中的小错误,即使我设置 String strThatDay = "2010/10/03";,我也有 274 天的差距;应该只有 1天,感谢支持
  • @Paresh,很抱歉,("yyyy/mm/dd"); 应该替换为 ("yyyy/MM/dd"); 它是大写的 M 代表月份,小写代表分钟。已更正。
  • @Gevorg,我确实推荐过它。 :) 我古斯塔乔达时间
  • 有时在除以毫秒时,由于舍入问题(缺少),这段代码会休息一天。这对我有用:Math.round(millisBetweenDates * 1f / TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS));
【解决方案2】:

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

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

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

或尝试将TimeZone 作为参数传递给daysBetween(),并在sDateeDate 对象中调用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
}

getDatePart() 取自here

/**
 * 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

【讨论】:

  • 同意。使用顶级方法您将获得更可靠和优雅的解决方案。谢谢!
  • 对于方法:daysBetween 如果日期是 2012 年 7 月 24 日的 15:00 并且 endDate 是 2012 年 7 月 24 日的 16:00 - 那么日期在 endDate 之前,但是不是一整天,而只是一小时。在这种情况下,我是否遗漏了什么或者 daysBetween 的结果是错误的(因为预期结果为零,但给定的计算结果应该是 1 而不是零)?
  • @Zainodis,在我的脑海中,我是否更新了代码。我想这应该可以解决问题。
  • @SamQuest 感谢更新!我采取了一种更天真的方法:停止带有 sDate.before(eDate) 的 while 循环并返回结果,如果 start 和 end 在同一天、同一个月和同一年。这也确保了,如果在第一次迭代中,开始和结束在同一天/月/年(尽管时间方面的开始在结束之前),则正确返回零。
  • 你先生,应该得到一个铃铛!
【解决方案3】:

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

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

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

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

就是这样!

【讨论】:

  • 这也对我有用.. 其他的太复杂了,太准确了:)
  • 先减后除会更好,防止除两次。
  • @ravindu1024 如果 startDate 小于 endDate,这样做会产生 +1 的差异。在这种情况下有 +1 的差异。可以通过在答案中添加 -1 来解决。
  • @sHOLE 怎么样?我的意思是你应该做 (t1-t2)/C 而不是 t1/C - t2/C。由于 t1/C 和 t2/C 都不会为零,我看不出这会如何影响答案。
  • @ravindu1024 我明白你想说什么,当我读到这个答案时我也想知道。只有在实施之后,我才注意到为什么没有这样做(我上面提到的原因)。
【解决方案4】:

使用jodatime API

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

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

还有一个android specific JodaTime library

【讨论】:

  • 感谢支持,但如果使用 Android/JAVA 代码完成,不乐意使用其他 API
  • 乔达+1。 Java 日历 API 非常混乱,而 Joda 干净漂亮。
  • JodaTime 在 Android 的几个设备上给出了几个错误,我不知道为什么,我有几个问题
  • Joda 时间库将为您的项目添加 4744 种方法。如果您想避免 65K 方法的限制,请明智地选择。
【解决方案5】:

这个片段考虑了夏令时并且是 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));
}

【讨论】:

    【解决方案6】:

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

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

    【讨论】:

    • @PareshMayani 刚刚签入日志猫
    【解决方案7】:

    tl;博士

    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 TutorialWikipedia 了解更多信息。


    关于java.time

    java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.DateCalendarSimpleDateFormat

    Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。

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

    从哪里获得 java.time 类?

    ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。您可以在这里找到一些有用的类,例如IntervalYearWeekYearQuartermore

    【讨论】:

    • java.time.LocalDate 在 Android 中不受支持
    • @MahdiAstanei 重读我关于 Android 的 ThreeTenABP 库的第三段。非常值得添加到您的应用中,因为旧的日期时间类确实很糟糕。
    【解决方案8】:

    Sam Quest 的答案中的 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);
    }
    

    【讨论】:

      【解决方案9】:

      最好和最简单的方法

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

      【讨论】:

        【解决方案10】:

        使用以下函数:

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

        【讨论】:

          【解决方案11】:

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

          问题在于,我看到的所有答案——使用 Joda、Calendar、Date 或其他任何东西——只考虑了毫秒数。他们最终计算的是两个日期之间的 24 小时周期数,而不是实际的天数。因此,从 1 月 1 日晚上 11 点到 1 月 2 日凌晨 1 点的时间将返回 0 天。

          要计算startDateendDate 之间的实际天数,只需执行以下操作:

          // 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 has suggested,但我认为代码更小。

          【讨论】:

            【解决方案12】:

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

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

            如果您需要日期之间的天数(不包括后一个日期),请在看到 endDay - startDay + 1 时去掉 + 1

            【讨论】:

              【解决方案13】:

              另一种方式:

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

              【讨论】:

              • 请对您提供的代码发表评论。以便人们理解您的代码的含义。
              【解决方案14】:
                      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));
              

              【讨论】:

                【解决方案15】:

                使用这些功能

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

                【讨论】:

                • 这段代码使用了麻烦的旧日期时间类,现在已被 java.time 类取代。对于较旧的 Java 和 Android,请参阅 ThreeTen-BackportThreeTenABP 项目。
                • 日历类是旧的日期时间类吗?
                • 是的,在 java.time 包之外发现的任何与日期时间相关的类现在都是遗留的,应该避免使用。这包括DateCalendar,以及java.sql 类。请参阅 Oracle 教程。
                【解决方案16】:
                        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();
                
                
                }
                

                【讨论】:

                  【解决方案17】:

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

                  假设您在 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
                  }
                  

                  【讨论】:

                    【解决方案18】:

                    乔达时间

                    最好的方法是使用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'
                    }
                    

                    【讨论】:

                    • 好答案。请注意,在Duration 上调用toString 会以ISO 8601 标准格式之一PnYnMnDTnHnMnS 生成字符串表示。 P 标志着开始,而T 将年-月-日与小时-分钟-秒分开。所以P3D 是三天,P3DT12H 是三天半。
                    • Joda 时间库将为您的项目添加 4744 种方法。如果您想避免 65K 方法的限制,请明智地选择。
                    • 这里需要改成DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd")
                    猜你喜欢
                    • 2015-12-19
                    • 1970-01-01
                    • 2019-02-15
                    • 1970-01-01
                    • 1970-01-01
                    • 2014-06-13
                    • 1970-01-01
                    • 2016-11-23
                    • 1970-01-01
                    相关资源
                    最近更新 更多