首页 文章

如何比较Java中的日期? [重复]

提问于
浏览
337

这个问题在这里已有答案:

如何比较Java之间的日期?

例:

date1是 22-02-2010
date2今天是 07-04-2010
date3是 25-12-2010

date3 始终大于 date1date2 始终是今天 . 如何验证今天的日期是否在date1和date3之间?

11 回答

  • 522

    使用getTime()获取日期的数值,然后使用返回的值进行比较 .

  • 20

    试试这个

    public static boolean compareDates(String psDate1, String psDate2) throws ParseException{
            SimpleDateFormat dateFormat = new SimpleDateFormat ("dd/MM/yyyy");
            Date date1 = dateFormat.parse(psDate1);
            Date date2 = dateFormat.parse(psDate2);
            if(date2.after(date1)) {
                return true;
            } else {
                return false;
            }
        }
    
  • 15

    Datebeforeafter方法,可以compared to each other如下:

    if(todayDate.after(historyDate) && todayDate.before(futureDate)) {
        // In between
    }
    

    对于包容性比较:

    if(!historyDate.after(todayDate) && !futureDate.before(todayDate)) {
        /* historyDate <= todayDate <= futureDate */ 
    }
    

    你也可以给Joda-Time一个去,但请注意:

    Joda-Time是Java SE 8之前Java的事实标准日期和时间库 . 现在要求用户迁移到java.time(JSR-310) .

    后端端口可用于Java 6和7以及Android .

  • 86

    使用compareTo

    date1.compareTo(date2);

  • 5

    以下是比较日期的最常用方法 . 但我更喜欢第一个

    Approach-1 : Using Date.before(), Date.after() and Date.equals()

    if(date1.after(date2)){
                    System.out.println("Date1 is after Date2");
                }
    
                if(date1.before(date2)){
                    System.out.println("Date1 is before Date2");
                }
    
                if(date1.equals(date2)){
                    System.out.println("Date1 is equal Date2");
                }
    

    Approach-2 : Date.compareTo()

    if(date1.compareTo(date2)>0){
                    System.out.println("Date1 is after Date2");
                }else if(date1.compareTo(date2)<0){
                    System.out.println("Date1 is before Date2");
                }else{
                    System.out.println("Date1 is equal to Date2");
                }
    

    Approach-3 : Calender.before(), Calender.after() and Calender.equals()

    Calendar cal1 = Calendar.getInstance();
                Calendar cal2 = Calendar.getInstance();
                cal1.setTime(date1);
                cal2.setTime(date2);
    
                if(cal1.after(cal2)){
                    System.out.println("Date1 is after Date2");
                }
    
                if(cal1.before(cal2)){
                    System.out.println("Date1 is before Date2");
                }
    
                if(cal1.equals(cal2)){
                    System.out.println("Date1 is equal Date2");
                }
    
  • 116

    tl;博士

    LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) ) ;
    Boolean isBetween = 
        ( ! today.isBefore( localDate1 ) )  // “not-before” is short for “is-equal-to or later-than”.
        &&
        today.isBefore( localDate3 ) ;
    

    或者,更好的是,如果您将ThreeTen-Extra库添加到项目中 .

    LocalDateRange.of(
        LocalDate.of( … ) ,
        LocalDate.of( … )
    ).contains(
        LocalDate.now()
    )
    

    半开放方式,开始是包容性的,而结束是排他性的 .

    格式选择不当

    顺便说一句,对于日期或日期时间值的文本表示,这是一种错误的格式选择 . 只要有可能,坚持使用标准的ISO 8601格式 . ISO 8601格式是明确的,可以在人类文化中理解,并且易于通过机器解析 .

    对于仅日期值,标准格式为YYYY-MM-DD . 请注意,这种格式在按字母顺序排序时具有按时间顺序排列的优点 .

    LocalDate

    LocalDate类表示没有时间且没有时区的仅日期值 .

    时区对于确定日期至关重要 . 对于任何给定的时刻,日期在全球范围内因地区而异 . 例如,在Paris France午夜后几分钟是新的一天,而在Montréal Québec仍然是“昨天” .

    ZoneId z = ZoneId.of( "America/Montreal" );
    LocalDate today = LocalDate.now( z );
    

    DateTimeFormatter

    由于您的输入字符串是非标准格式,我们必须定义要匹配的格式设置模式 .

    DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" );
    

    用它来解析输入字符串 .

    LocalDate start = LocalDate.parse( "22-02-2010" , f );
    LocalDate stop = LocalDate.parse( "25-12-2010" , f );
    

    在日期时间工作中,通常最好通过半开放方法定义时间 Span ,其中开头是包含在内的,而结尾是独占的 . 因此,我们想知道今天是否与开始时相同或晚于停止之前 . 一种简单的说法“与开始相同或晚于”的方式是“不在开始之前” .

    Boolean intervalContainsToday = ( ! today.isBefore( start ) ) && today.isBefore( stop ) ;
    

    请参阅the Answer by gstackoverflow,其中显示了您可以调用的比较方法列表 .


    关于java.time

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

    现在位于maintenance modeJoda-Time项目建议迁移到java.time类 .

    要了解更多信息,请参阅Oracle Tutorial . 并搜索Stack Overflow以获取许多示例和解释 . 规格是JSR 310 .

    从哪里获取java.time类?

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


    更新:下面的“Joda-Time”部分保留为历史记录 . 现在位于maintenance modeJoda-Time项目建议迁移到java.time类 .

    Joda-Time

    关于捆绑的java.util.Date和java.util.Calendar类,其他答案是正确的 . 但这些课程非常麻烦 . 所以这是使用Joda-Time 2.3库的一些示例代码 .

    如果你真的想要一个没有任何时间部分和没有时区的日期,那么在Joda-Time中使用LocalDate类 . 该类提供了比较方法,包括 compareTo (与Java Comparators一起使用),_ isBeforeisAfterisEqual .

    输入...

    String string1 = "22-02-2010";
    String string2 = "07-04-2010";
    String string3 = "25-12-2010";
    

    定义描述输入字符串的格式化程序......

    DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd-MM-yyyy" );
    

    使用formatter进行解析将字符串转换为LocalDate对象......

    LocalDate localDate1 = formatter.parseLocalDate( string1 );
    LocalDate localDate2 = formatter.parseLocalDate( string2 );
    LocalDate localDate3 = formatter.parseLocalDate( string3 );
    
    boolean is1After2 = localDate1.isAfter( localDate2 );
    boolean is2Before3 = localDate2.isBefore( localDate3 );
    

    转储到控制台......

    System.out.println( "Dates: " + localDate1 + " " + localDate2 + " " + localDate3 );
    System.out.println( "is1After2 " + is1After2 );
    System.out.println( "is2Before3 " + is2Before3 );
    

    跑的时候......

    Dates: 2010-02-22 2010-04-07 2010-12-25
    is1After2 false
    is2Before3 true
    

    那么看看第二个是否在另外两个之间(完全,意思是不等于任何一个 endpoints )......

    boolean is2Between1And3 = ( ( localDate2.isAfter( localDate1 ) ) && ( localDate2.isBefore( localDate3 ) ) );
    

    与时间 Span 合作

    如果您正在使用时间 Span ,我建议您在Joda-Time中探索类:DurationIntervalPeriod . 诸如 overlapcontains 之类的方法使比较变得容易 .

    对于文本表示,请查看ISO 8601标准:

    • duration
      格式:PnYnMnDTnHnMnS
      示例:P3Y6M4DT12H30M5S
      (表示“三年,六年,四天,十二小时,三十五,五秒”)

    • interval
      格式:开始/结束
      示例:2007-03-01T13:00:00Z / 2008-05-11T15:30:00Z

    Joda-Time类可以使用这两种格式的字符串,包括输入(解析)和输出(生成字符串) .

    Joda-Time使用 Half-Open 方法进行比较,其中 Span 的开始是包含的,而结尾是独占的 . 这种方法对于处理时间 Span 是明智的 . 搜索StackOverflow以获取更多信息 .

  • 4

    比较两个日期:

    Date today = new Date();                   
      Date myDate = new Date(today.getYear(),today.getMonth()-1,today.getDay());
      System.out.println("My Date is"+myDate);    
      System.out.println("Today Date is"+today);
      if (today.compareTo(myDate)<0)
          System.out.println("Today Date is Lesser than my Date");
      else if (today.compareTo(myDate)>0)
          System.out.println("Today Date is Greater than my date"); 
      else
          System.out.println("Both Dates are equal");
    
  • 0

    Java 8及更高版本的更新

    这些方法存在于LocalDateLocalTimeLocalDateTime类中 .

    这些类内置于Java 8及更高版本中 . 大部分java.time功能在ThreeTen-Backport中反向移植到Java 6和7,并进一步适应ThreeTenABP中的Android(参见How to use…) .

  • 0

    你可以使用Date.getTime()

    返回自此Date对象表示的1970年1月1日00:00:00 GMT以来的毫秒数 .

    这意味着您可以像数字一样比较它们:

    if (date1.getTime() <= date.getTime() && date.getTime() <= date2.getTime()) {
        /*
         * date is between date1 and date2 (both inclusive)
         */
    }
    
    /*
     * when date1 = 2015-01-01 and date2 = 2015-01-10 then
     * returns true for:
     * 2015-01-01
     * 2015-01-01 00:00:01
     * 2015-01-02
     * 2015-01-10
     * returns false for:
     * 2014-12-31 23:59:59
     * 2015-01-10 00:00:01
     * 
     * if one or both dates are exclusive then change <= to <
     */
    
  • 23

    此代码确定今天是基于KOREA语言环境的某个持续时间

    Calendar cstart = Calendar.getInstance(Locale.KOREA);
        cstart.clear();
        cstart.set(startyear, startmonth, startday);
    
    
        Calendar cend = Calendar.getInstance(Locale.KOREA);
        cend.clear();
        cend.set(endyear, endmonth, endday);
    
        Calendar c = Calendar.getInstance(Locale.KOREA);
    
        if(c.after(cstart) && c.before(cend)) {
            // today is in startyear/startmonth/startday ~ endyear/endmonth/endday
        }
    
  • 10

    这个方法对我有用:

    public static String daysBetween(String day1, String day2) {
        String daysBetween = "";
        SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
        try {
            Date date1 = myFormat.parse(day1);
            Date date2 = myFormat.parse(day2);
            long diff = date2.getTime() - date1.getTime();
            daysBetween = ""+(TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return daysBetween;
    }
    

相关问题