java 如何检查日期是否超过 7 天

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30207693/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 16:39:54  来源:igfitidea点击:

How to check if date exceeds more than seven days

javadatecompare

提问by CodeNotFound

I would like to check if two date exceeds a week, like, check if two dates have seven days,

我想检查两个日期是否超过一周,例如检查两个日期是否有 7 天,

at point the data range should be within a week only(7 Days).

此时数据范围应仅在一周内(7 天)。

i have tried something like this,

我试过这样的事情,

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class IsDateRangeExceedsWeek 
{
    public static void main( String[] args ) 
    {
        try{

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date fromDate = sdf.parse("2015-05-01");
            Date toDate = sdf.parse("2015-05-07");

            System.out.println(sdf.format(fromDate));
            System.out.println(sdf.format(toDate));

            if(fromDate.compareTo(toDate)>0){
                System.out.println("From Date should be less than To Date");
            } else if(fromDate.compareTo(toDate)==0){
                System.out.println("From Date is equal to To Date");
            } 

        }catch(ParseException ex){
            ex.printStackTrace();
        }
    }
}

Could some one help ?

有人可以帮忙吗?

回答by Veselin Davidov

The easiest way is to use Jodatimeand use

最简单的方法是使用Jodatime并使用

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

Another solution is to use Calendar, add 7 days and compare again.

另一种解决方案是使用日历,添加 7 天并再次比较。

  Calendar c=Calendar.getInstance();
  c.setTime(fromDate);
  c.add(Calendar.DATE,7);
  if(c.getTime().compareTo(toDate)<0){
    It's more than 7 days.
  }

回答by Misha

Using the java.timeclasses built into Java 8 and later:

使用Java 8 及更高版本中内置的java.time类:

LocalDate from = LocalDate.parse("2015-05-01");
LocalDate to = LocalDate.parse("2015-05-07");

long days = ChronoUnit.DAYS.between(from, to);    // 6 days
long weeks = ChronoUnit.WEEKS.between(from, to);  // 0 weeks

回答by Rahul Tripathi

You can try like this:

你可以这样试试:

if(Days.daysBetween(fromDate,toDate ).getDays()>7)

Check JodaTime API

检查JodaTime API