【问题标题】:Compare date by day length - JAVA [duplicate]按日长比较日期 - JAVA [重复]
【发布时间】:2014-10-31 17:53:28
【问题描述】:

我想问你,如果你帮我解决这个问题...

我有两个约会:

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date1 = sdf.parse("2009-12-31"); 
        Date date2 = sdf.parse("2010-01-31");

我想比较一个日期,他们是否相差X天

        int x = 30; // I need to delete the file if it is older than 30 days

        if(isOldThan30days(date1,date2, x)){
           //delete file
        }else{
           //nothing
        }

我希望你能理解我:-)。我怎样才能做到这一点?谢谢。

【问题讨论】:

  • Java 8 Period betweenDates = Period.between(startDate, endDate); int diffMonths = betweenDates.getMonths()

标签: java date


【解决方案1】:

您可以尝试这样来获取两个日期之间的天数:

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

那么你可以这样做:

if(days > 30)
{
  //delete files
}
else
{
  //whatever
}

【讨论】:

【解决方案2】:

针对该问题使用Calendar

    Calendar c1 = new GregorianCalendar();
    c1.setTime(date1);

    Calendar c2 = new GregorianCalendar();
    c2.setTime(new Date());

    c1.add(Calendar.DAY_OF_MONTH, 30);

    if (c2.after(c1)){
        //delete Fiels
    }

【讨论】:

  • 但是,在你的代码中:c1=c2 ?
  • @user3784463 对不起我的错,已经改变了我的答案。
猜你喜欢
  • 2017-03-19
  • 1970-01-01
  • 2011-02-14
  • 2014-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-17
  • 1970-01-01
相关资源
最近更新 更多