【问题标题】:Check date with todays date用今天的日期检查日期
【发布时间】:2011-09-26 02:57:16
【问题描述】:

我编写了一些代码来检查两个日期,一个开始日期和一个结束日期。如果结束日期早于开始日期,则会提示结束日期早于开始日期。

我还想检查开始日期是否早于今天(今天与用户使用应用程序的日期相同)我该怎么做? (下面的日期检查器代码,如果有任何影响,所有这些都是为 android 编写的)

if (startYear > endYear) {
    fill = fill + 1;
    message = message + "End Date is Before Start Date" + "\n";
} else if (startMonth > endMonth && startYear >= endYear) {
    fill = fill + 1;
    message = message + "End Date is Before Start Date" + "\n";
} else if (startDay > endDay && startMonth >= endMonth && startYear >= endYear) {
    fill = fill + 1;
    message = message + "End Date is Before Start Date" + "\n";
}

【问题讨论】:

    标签: java android date


    【解决方案1】:

    tl;博士

    LocalDate
    .parse( "2021-01-23" )
    .isBefore(
        LocalDate.now(
            ZoneId.of( "Africa/Tunis" ) 
        )
    )
    

    … 或:

    try 
    {
        org.threeten.extra.LocalDateRange range =         
            LocalDateRange.of( 
                LocalDate.of( "2021-01-23" ) ,
                LocalDate.of( "2021-02-21" )
            )
        ;
        if( range.isAfter( 
            LocalDate.now( ZoneId.of( "Africa/Tunis" ) )
        ) { … }
        else { … handle today being within or after the range. }
    } catch ( java.time.DateTimeException e ) {
        // Handle error where end is before start.
    }
    

    详情

    其他答案忽略了time zone的关键问题。

    其他答案使用过时的类。

    避免使用旧的日期时间类

    与最早的 Java 版本捆绑在一起的旧日期时间类设计不佳、令人困惑且麻烦。避免使用 java.util.Date/.Calendar 和相关类。

    java.time

    LocalDate

    对于仅日期值、没有时间和时区,请使用 LocalDate 类。

    LocalDate start = LocalDate.of( 2016 , 1 , 1 );
    LocalDate stop = start.plusWeeks( 1 );
    

    时区

    请注意,虽然LocalDate 不存储时区,但确定诸如“今天”之类的日期需要时区。对于任何给定的时刻,日期可能因世界各地的时区而异。例如,巴黎的新一天比蒙特利尔更早。巴黎午夜过后的片刻,蒙特利尔仍是“昨天”。

    如果您只有offset-from-UTC,请使用ZoneOffset。如果您有完整的时区(大陆/地区),请使用ZoneId。如果您想要 UTC,请使用方便的常量 ZoneOffset.UTC。

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

    使用isEqual、isBefore 和isAfter 方法可以轻松进行比较。

    boolean invalidInterval = stop.isBefore( start );
    

    我们可以检查今天是否包含在此日期范围内。在这里显示的逻辑中,我使用 Half-Open 方法,其中开头是 inclusive 而结尾是 exclusive。这种方法在日期时间工作中很常见。因此,例如,一周从星期一一直到但不包括下星期一。

    // Is today equal or after start (not before) AND today is before stop.
    boolean intervalContainsToday = ( ! today.isBefore( start ) ) && today.isBefore( stop ) ) ;
    

    LocalDateRange

    如果在这样的时间范围内进行大量工作,请考虑将ThreeTen-Extra 库添加到您的项目中。该库扩展了 java.time 框架,并且是可能添加到 java.time 的试验场。

    ThreeTen-Extra 包含一个 LocalDateRange 类和方便的方法,例如 abuts、contains、encloses、overlaps 等。


    关于java.time

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

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

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

    您可以直接与您的数据库交换 java.time 对象。使用符合JDBC 4.2 或更高版本的JDBC driver。不需要字符串,不需要java.sql.* 类。

    从哪里获取 java.time 类?

    【讨论】:

    • 太罗嗦了。答案埋在中间。如果您愿意,最好在顶部回答并详细说明。
    • @Sun 我在顶部添加了一个“tl;dr”部分。谢谢。
    【解决方案2】:

    使用纯Java:

    public static boolean isToday(Date date){
            Calendar today = Calendar.getInstance();
            Calendar specifiedDate  = Calendar.getInstance();
            specifiedDate.setTime(date);
    
            return today.get(Calendar.DAY_OF_MONTH) == specifiedDate.get(Calendar.DAY_OF_MONTH)
                    &&  today.get(Calendar.MONTH) == specifiedDate.get(Calendar.MONTH)
                    &&  today.get(Calendar.YEAR) == specifiedDate.get(Calendar.YEAR);
        }
    

    【讨论】:

      【解决方案3】:
      public static boolean itIsToday(long date){
          boolean result = false;
          try{
              Calendar calendarData = Calendar.getInstance();
              calendarData.setTimeInMillis(date);
              calendarData.set(Calendar.HOUR_OF_DAY, 0);
              calendarData.set(Calendar.MINUTE, 0);
              calendarData.set(Calendar.SECOND, 0);
              calendarData.set(Calendar.MILLISECOND, 0);
      
              Calendar calendarToday = Calendar.getInstance();
              calendarToday.setTimeInMillis(System.currentTimeMillis());
              calendarToday.set(Calendar.HOUR_OF_DAY, 0);
              calendarToday.set(Calendar.MINUTE, 0);
              calendarToday.set(Calendar.SECOND, 0);
              calendarToday.set(Calendar.MILLISECOND, 0);
      
              if(calendarToday.getTimeInMillis() == calendarData.getTimeInMillis()) {
                  result = true;
              }
          }catch (Exception exception){
              Log.e(TAG, exception);
          }
          return result;
      }
      

      【讨论】:

      • 随着 JSR 310 的采用,这些类在几年前就成为了遗产。建议在 2019 年使用它们是一个糟糕的建议。只使用 java.time 类。
      【解决方案4】:

      Android 已经为此提供了一个专门的类。检查DateUtils.isToday(long when)

      【讨论】:

      • 完美而简单。谢谢!
      【解决方案5】:

      不要那么复杂。使用这种简单的方法。导入 DateUtils java 类并调用以下返回布尔值的方法。

      DateUtils.isSameDay(date1,date2);
      DateUtils.isSameDay(calender1,calender2);
      DateUtils.isToday(date1);
      

      更多信息请参考这篇文章DateUtils Java

      【讨论】:

      • 这很简单,做这个。
      • 嗯,这可能很容易,但重要的是人们要理解这是示例代码,似乎没有测试/覆盖。它在这里作为您可以拉入的一些库呈现,但它与其他答案中的其他代码 sn-ps 没有什么不同。正如其他人所提到的,最好使用 Joda 或 Commons 之类的库,因为您可以依赖他们的社区维护。很抱歉选择您的答案,其他人可能会遇到同样的问题。 请,请尽可能使用图书馆。如果您必须从网络上复制代码,请务必在投入生产之前进行测试和理解。
      • 我收到错误:The method isToday() is undefined for the type DateUtils.
      • @learner 这个方法只存在于 Android 版本的 DateUtils 中。对于“桌面”JDK 使用 DateUtils.isSameDay(someday, new Date());
      • 我相信这是来自 apache commons lang
      【解决方案6】:

      试试这个:

      public static boolean isToday(Date date)
      {
          return org.apache.commons.lang3.time.DateUtils.isSameDay(Calendar.getInstance().getTime(),date);
      }
      

      【讨论】:

        【解决方案7】:

        执行此操作的另一种方法:

        public class TimeUtils {
        
            /**
             * @param timestamp
             * @return
             */
            public static boolean isToday(long timestamp) {
                Calendar now = Calendar.getInstance();
                Calendar timeToCheck = Calendar.getInstance();
                timeToCheck.setTimeInMillis(timestamp);
                return (now.get(Calendar.YEAR) == timeToCheck.get(Calendar.YEAR)
                        && now.get(Calendar.DAY_OF_YEAR) == timeToCheck.get(Calendar.DAY_OF_YEAR));
            }
        
        }
        

        【讨论】:

          【解决方案8】:

          这有帮助吗?

          Calendar c = Calendar.getInstance();
          
          // set the calendar to start of today
          c.set(Calendar.HOUR_OF_DAY, 0);
          c.set(Calendar.MINUTE, 0);
          c.set(Calendar.SECOND, 0);
          c.set(Calendar.MILLISECOND, 0);
          
          // and get that as a Date
          Date today = c.getTime();
          
          // or as a timestamp in milliseconds
          long todayInMillis = c.getTimeInMillis();
          
          // user-specified date which you are testing
          // let's say the components come from a form or something
          int year = 2011;
          int month = 5;
          int dayOfMonth = 20;
          
          // reuse the calendar to set user specified date
          c.set(Calendar.YEAR, year);
          c.set(Calendar.MONTH, month);
          c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
          
          // and get that as a Date
          Date dateSpecified = c.getTime();
          
          // test your condition
          if (dateSpecified.before(today)) {
            System.err.println("Date specified [" + dateSpecified + "] is before today [" + today + "]");
          } else {
            System.err.println("Date specified [" + dateSpecified + "] is NOT before today [" + today + "]");
          }
          

          【讨论】:

          • 不应该一开始也将millis重置为零吗?
          • 使用 Joda Time 的 DateMidnight,您无需重置任何内容。
          • 毫秒也需要重置 c.set(Calendar.MILLISECOND, 0);如果你不这样做,如果你比较同一天的日期会有问题。
          • 使用Calendar. HOUR 是错误的,因为它不会重置 AM/PM 属性,因此如果当前时间是下午 13 点,则结果小时数将是下午 12 点。请改用Calendar. HOUR_OF_DAY。
          • 更新:这些糟糕的日期时间类现在被 JSR 310 中定义的现代 java.time 类所取代。
          【解决方案9】:
              boolean isBeforeToday(Date d) {
                  Date today = new Date();
                  today.setHours(0);
                  today.setMinutes(0);
                  today.setSeconds(0);
                  return d.before(today);
              }
          

          【讨论】:

            【解决方案10】:

            要检查日期是否是今天的日期,或者不仅检查日期不包含在其中的日期,因此将时间设为 00:00:00 并使用下面的代码

                Calendar c = Calendar.getInstance();
            
                // set the calendar to start of today
                c.set(Calendar.HOUR_OF_DAY, 0);
                c.set(Calendar.MINUTE, 0);
                c.set(Calendar.SECOND, 0);
                c.set(Calendar.MILLISECOND, 0);
            
                Date today = c.getTime();
            
                // or as a timestamp in milliseconds
                long todayInMillis = c.getTimeInMillis();
            
            
                int dayOfMonth = 24;
                int month = 4;
                int year =2013;
            
                // reuse the calendar to set user specified date
                c.set(Calendar.YEAR, year);
                c.set(Calendar.MONTH, month - 1);
                c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                c.set(Calendar.HOUR_OF_DAY, 0);
                c.set(Calendar.MINUTE, 0);
                c.set(Calendar.SECOND, 0);
                c.set(Calendar.MILLISECOND, 0);
                // and get that as a Date
                Date dateSpecified = c.getTime();
            
                // test your condition
                if (dateSpecified.before(today)) {
            
                    Log.v(" date is previou")
                } else if (dateSpecified.equal(today)) {
            
                    Log.v(" date is today ")
                } 
                         else if (dateSpecified.after(today)) {
            
                    Log.v(" date is future date ")
                } 
            

            希望对您有所帮助....

            【讨论】:

              【解决方案11】:

              使用Joda Time可以简化为:

              DateMidnight startDate = new DateMidnight(startYear, startMonth, startDay);
              if (startDate.isBeforeNow())
              {
                  // startDate is before now
                  // do something...
              }
              

              【讨论】:

              • 现在已弃用!
              • 在月份参数中也要非常小心 - Joda 的范围是 1-12,Java 的范围是 0-11。如果月份是一月并且从 Java 传递,则可以抛出 IllegalArgument 异常。虽然没有记录,但如果值无效,它会抛出 org.joda.time.IllegalFieldValueException(IllegalArgumentException 的子类)。
              • 很好的提示,但无论如何 IMO Joda 的范围是正确的。 0-11 对我来说从来没有意义。
              【解决方案12】:

              我假设您使用整数来表示您的年、月和日?如果要保持一致,请使用 Date 方法。

              Calendar cal = new Calendar();
              int currentYear, currentMonth, currentDay; 
              currentYear = cal.get(Calendar.YEAR); 
              currentMonth = cal.get(Calendar.MONTH); 
              currentDay = cal.get(Calendar.DAY_OF_WEEK);
              
                   if(startYear < currentYear)
                              {
                                  message = message + "Start Date is Before Today" + "\n";
                              }
                          else if(startMonth < currentMonth && startYear <= currentYear)
                                  {
                                      message = message + "Start Date is Before Today" + "\n";
                                  }
                          else if(startDay < currentDay && startMonth <= currentMonth && startYear <= currentYear)
                                      {
                                          message = message + "Start Date is Before Today" + "\n";
                                      }
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2014-09-13
                • 1970-01-01
                • 2018-04-05
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2016-03-06
                相关资源
                最近更新 更多