【问题标题】:Java Date difference in terms of days [duplicate]Java日期差异以天为单位[重复]
【发布时间】:2015-12-19 04:37:36
【问题描述】:

谁能帮我以有效的方式计算Date的天数差异?

Date nextCollectionDate = dispenseNormal.getDispensing().getNextCollectionDate();
Date currentDate = new Date();
int daysDiff = currentDate - nextCollectionDate;

【问题讨论】:

  • 您到底期待什么?你得到什么?有什么问题?
  • 我想以天为单位计算两个日期之间的差异。
  • 使用 Java 8 的 Time API、JodaTime 甚至 Calendar
  • 另一个选项是使用GregorianCalendar

标签: java date


【解决方案1】:

您可以使用JodaTime,这是对这些场景非常有用的 API

int days = Days.daysBetween(date1, date2).getDays();

否则您可以创建自己的方法并获得差异

public long getDays(Date d1, Date d2) 
{
    long l = d2.getTime() - d1.getTime();
    return TimeUnit.DAYS.convert(l, TimeUnit.MILLISECONDS);
}

【讨论】:

    【解决方案2】:
    //diff in msec
    long diff = currentDate.getTime() - nextCollectionDate.getTime();
    
    //diff in days
    long days = diff / (24 * 60 * 60 * 1000);
    

    【讨论】:

      【解决方案3】:

      你可以使用joda api

      下面的代码应该可以解决您的查询

       Date nextCollectionDate = dispenseNormal.getDispensing().getNextCollectionDate();
          Date currentDate = new Date();
          Days  d = Days.daysBetween(new DateTime(nextCollectionDate ), new DateTime(currentDate ))
      
          int daysDiff = d.getDays();
      

      【讨论】:

        【解决方案4】:

        我建议你在 Java 8 中使用 LocalDate:

        LocalDate startDate = LocalDate.now().minusDays(1);
        LocalDate endDate = LocalDate.now();
        long days = Period.between(startDate, endDate).getDays();
        System.out.println("No of days: " + days);
        

        按预期打印:

        No of days: 1
        

        【讨论】:

          猜你喜欢
          • 2011-04-19
          • 2019-02-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-09-29
          • 2014-06-13
          • 1970-01-01
          • 2015-03-23
          相关资源
          最近更新 更多