【问题标题】:Best way to compare dates in Android在 Android 中比较日期的最佳方法
【发布时间】:2012-06-02 05:50:50
【问题描述】:

我正在尝试将字符串格式的日期与当前日期进行比较。这就是我的做法(尚未测试,但应该可以),但我使用的是不推荐使用的方法。有什么好的替代方案吗?谢谢。

附:我真的很讨厌用 Java 做 Date 的东西。有很多方法可以做同样的事情,你真的不确定哪一种是正确的,因此我的问题在这里。

String valid_until = "1/1/1990";

Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");
Date strDate = sdf.parse(valid_until);

int year = strDate.getYear(); // this is deprecated
int month = strDate.getMonth() // this is deprecated
int day = strDate.getDay(); // this is deprecated       

Calendar validDate = Calendar.getInstance();
validDate.set(year, month, day);

Calendar currentDate = Calendar.getInstance();

if (currentDate.after(validDate)) {
    catalog_outdated = 1;
}

【问题讨论】:

标签: java android datetime


【解决方案1】:

您的代码可以简化为

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(valid_until);
if (new Date().after(strDate)) {
    catalog_outdated = 1;
}

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(valid_until);
if (System.currentTimeMillis() > strDate.getTime()) {
    catalog_outdated = 1;
}

【讨论】:

  • 它确实有效,我在其他线程中发布了相同的解决方案但不是在这里,因为同事更快 O_o。
  • 只是想确认一下,然后再接受。谢谢。它运行良好,简洁明了。
  • 我认为应该使用dd/MM/yyyy格式而不是dd/mm/yyyy,因为“m”表示分钟,“M”表示月份。
  • 使用 compareTo() 方法不是更好吗?
【解决方案2】:

您可以直接从Date 创建Calendar

Calendar validDate = new GregorianCalendar();
validDate.setTime(strDate);
if (Calendar.getInstance().after(validDate)) {
    catalog_outdated = 1;
}

【讨论】:

    【解决方案3】:

    将日期转换为日历并在那里进行计算。 :)

    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    
    int year = cal.get(Calendar.YEAR);
    int month = cal.geT(Calendar.MONTH);
    int day = cal.get(Calendar.DAY_OF_MONTH); //same as cal.get(Calendar.DATE)
    

    或者:

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    Date strDate = sdf.parse(valid_until);
    
    if (strDate.after(new Date()) {
        catalog_outdated = 1;
    }
    

    【讨论】:

    • 请不要混淆任何人.. mm和MM是不同的!
    • @Muklas ? 8 年,这一直是错误的! ?更新!
    【解决方案4】:

    您可以使用 validDate.setTime(strDate) 查看http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html的javadoc

    【讨论】:

      【解决方案5】:

      你可以试试这个

      Calendar today = Calendar.getInstance (); 
      today.add(Calendar.DAY_OF_YEAR, 0); 
      today.set(Calendar.HOUR_OF_DAY, hrs); 
      today.set(Calendar.MINUTE, mins ); 
      today.set(Calendar.SECOND, 0); 
      

      您可以使用today.getTime() 检索值并进行比较。

      【讨论】:

        【解决方案6】:

        请注意,在代码工作之前,正确的格式是 ("dd/MM/yyyy")。 “mm”表示分钟!

        String valid_until = "01/07/2013";
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        Date strDate = null;
        try {
            strDate = sdf.parse(valid_until);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (new Date().after(strDate)) {
            catalog_outdated = 1;
        }
        

        【讨论】:

          【解决方案7】:
          SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd",Locale.getDefault());
          Calendar calendar1 = Calendar.getInstance();
          Calendar calendar2 = Calendar.getInstance();
          
          Date date1 = dateFormat.parse("2013-01-01");
          Date date2 = dateFormat.parse("2013-01-02");
          
          calendar1.setTime(date1);
          calendar2.setTime(date2);
          
          System.out.println("Compare Result : " + calendar2.compareTo(calendar1));
          System.out.println("Compare Result : " + calendar1.compareTo(calendar2));
          

          将此日历表示的时间与给定日历表示的时间进行比较。

          返回 如果两个日历的时间相等,则为 0,如果此日历的时间在另一个之前,则为 -1,如果此日历的时间在另一个之后,则为 1。

          【讨论】:

          • 谢谢..它帮助我。
          【解决方案8】:
          String date = "03/26/2012 11:00:00";
          String dateafter = "03/26/2012 11:59:00";
          SimpleDateFormat dateFormat = new SimpleDateFormat(
                  "MM/dd/yyyy hh:mm:ss");
          Date convertedDate = new Date();
          Date convertedDate2 = new Date();
          try {
              convertedDate = dateFormat.parse(date);
              convertedDate2 = dateFormat.parse(dateafter);
              if (convertedDate2.after(convertedDate)) {
                  txtView.setText("true");
              } else {
                  txtView.setText("false");
              }
          } catch (ParseException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
          

          它返回真。您还可以在date.beforedate.equal 的帮助下检查之前和相等。

          【讨论】:

            【解决方案9】:

            更新:Joda-Time 库现在处于维护模式,建议迁移到继承它的 java.time 框架.请参阅Answer by Ole V.V.


            乔达时间

            java.util.Date 和 .Calendar 类是出了名的麻烦。避开他们。使用 Joda-Time 或 Java 8 中的新 java.time 包。

            本地日期

            如果您想要仅日期而不需要时间,请使用 LocalDate 类。

            时区

            获取当前日期取决于时区。一个新的日期在蒙特利尔之前在巴黎滚动。指定所需的时区,而不是依赖于 JVM 的默认值。

            Joda-Time 2.3 中的示例。

            DateTimeFormat formatter = DateTimeFormat.forPattern( "d/M/yyyy" );
            LocalDate localDate = formatter.parseLocalDate( "1/1/1990" );
            boolean outdated = LocalDate.now( DateTimeZone.UTC ).isAfter( localDate );
            

            【讨论】:

              【解决方案10】:

              您可以使用compareTo()

              如果当前对象小于,CompareTo 方法必须返回负数 大于其他对象,如果当前对象大于则为正数 其他对象,如果两个对象相等则为零。

              // Get Current Date Time
              Calendar c = Calendar.getInstance();
              SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm aa");
              String getCurrentDateTime = sdf.format(c.getTime());
              String getMyTime="05/19/2016 09:45 PM ";
              Log.d("getCurrentDateTime",getCurrentDateTime); 
              // getCurrentDateTime: 05/23/2016 18:49 PM
              
              if (getCurrentDateTime.compareTo(getMyTime) < 0)
              {
              
              }
              else
              {
               Log.d("Return","getMyTime older than getCurrentDateTime "); 
              }
              

              【讨论】:

              • 仅供参考,java.util.Datejava.util.Calendarjava.text.SimpleDateFormat 等麻烦的旧日期时间类现在已被 java.time 类所取代。大多数 java.time 功能在 ThreeTen-Backport 项目中被反向移植到 Java 6 和 Java 7。进一步适用于ThreeTenABP 中的早期 Android (How to use ThreeTenABP…
              【解决方案11】:
              Calendar toDayCalendar = Calendar.getInstance();
              Date date1 = toDayCalendar.getTime();
              
              
              Calendar tomorrowCalendar = Calendar.getInstance();
              tomorrowCalendar.add(Calendar.DAY_OF_MONTH,1);
              Date date2 = tomorrowCalendar.getTime();
              
              // date1 is a present date and date2 is tomorrow date
              
              if ( date1.compareTo(date2) < 0 ) {
              
                //  0 comes when two date are same,
                //  1 comes when date1 is higher then date2
                // -1 comes when date1 is lower then date2
              
               }
              

              【讨论】:

              • 仅供参考,java.util.Datejava.util.Calendarjava.text.SimpleDateFormat 等麻烦的旧日期时间类现在已被 java.time 类所取代。大多数 java.time 功能在 ThreeTen-Backport 项目中被反向移植到 Java 6 和 Java 7。进一步适用于ThreeTenABP 中的早期 Android (How to use ThreeTenABP…
              【解决方案12】:

              有时我们需要列出日期,比如

              今天有小时

              昨天和昨天

              2017 年 6 月 23 日的其他日子

              为此,我们需要将当前时间与我们的数据进行比较。

              Public class DateUtil {
              
                  Public static int getDateDayOfMonth (Date date) {
                      Calendar calendar = Calendar.getInstance ();
                      Calendar.setTime (date);
                      Return calendar.get (Calendar.DAY_OF_MONTH);
                  }
              
                  Public static int getCurrentDayOfMonth () {
                      Calendar calendar = Calendar.getInstance ();
                      Return calendar.get (Calendar.DAY_OF_MONTH);
                  }
              
                  Public static String convertMillisSecondsToHourString (long millisSecond) {
                      Date date = new Date (millisSecond);
                      Format formatter = new SimpleDateFormat ("HH: mm");
                      Return formatter.format (date);
                  }
              
                  Public static String convertMillisSecondsToDateString (long millisSecond) {
                      Date date = new Date (millisSecond);
                      Format formatter = new SimpleDateFormat ("dd / MM / yyyy");
                      Return formatter.format (date);
                  }
              
                  Public static long convertToMillisSecond (Date date) {
                      Return date.getTime ();
                  }
              
                  Public static String compare (String stringData, String yesterday) {
              
                      String result = "";
              
                      SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss");
                      Date date = null;
              
                      Try {
                          Date = simpleDateFormat.parse (stringData);
                      } Catch (ParseException e) {
                          E.printStackTrace ();
                      }
              
                      Long millisSecond = convertToMillisSecond (date);
                      Long currencyMillisSecond = System.currentTimeMillis ();
              
                      If (currencyMillisSecond> millisSecond) {
                          Long diff = currencyMillisSecond - millisSecond;
                          Long day = 86400000L;
              
                          If (diff <day && getCurrentDayOfMonth () == getDateDayOfMonth (date)) {
                              Result = convertMillisSecondsToHourString (millisSecond);
              
                          } Else if (diff <(day * 2) && getCurrentDayOfMonth () -1 == getDateDayOfMonth (date)) {
                              Result = yesterday;
                          } Else {
                              Result = convertMillisSecondsToDateString (millisSecond);
                          }
                      }
              
                      Return result;
                  }
              }
              

              您也可以在GitHubpost 中查看此示例。

              【讨论】:

                【解决方案13】:

                是时候给出现代答案了。

                java.time 和 ThreeTenABP

                    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("d/M/u");
                    String validUntil = "1/1/1990";
                    LocalDate validDate = LocalDate.parse(validUntil, dateFormatter);
                    LocalDate currentDate = LocalDate.now(ZoneId.of("Pacific/Efate"));
                    if (currentDate.isAfter(validDate)) {
                        System.out.println("Catalog is outdated");
                    }
                

                我刚才运行这段代码的时候,输出是:

                目录已过时

                由于在所有时区都不会是相同的日期,因此请将明确的时区指定给 LocalDate.now。如果您希望目录在所有时区同时过期,您可以提供ZoneOffset.UTC,只要您告知用户您使用的是 UTC。

                我正在使用 java.time,现代 Java 日期和时间 API。您使用的日期时间类CalendarSimpleDateFormatDate 都设计不佳,幸运的是早已过时。此外,尽管名称为 Date 并不代表日期,而是时间点。这样做的一个后果是:即使今天是 2019 年 2 月 15 日,新创建的 Date 对象已经(因此不等于)解析 15/02/2019Date 对象之后。这让一些人感到困惑。与此相反,现代的LocalDate 是一个没有时间(也没有时区)的日期,因此代表今天日期的两个LocalDates 将始终相等。

                问题:我可以在 Android 上使用 java.time 吗?

                是的,java.time 在较旧和较新的 Android 设备上运行良好。它只需要至少 Java 6

                • 在 Java 8 及更高版本以及更新的 Android 设备(从 API 级别 26 起)中,现代 API 是内置的。
                • 在 Java 6 和 7 中获得 ThreeTen Backport,这是现代类的后向端口(JSR 310 的 ThreeTen;请参阅底部的链接)。
                • 在(较旧的)Android 上使用 ThreeTen Backport 的 Android 版本。它被称为 ThreeTenABP。并确保从 org.threeten.bp 导入日期和时间类以及子包。

                链接

                【讨论】:

                  【解决方案14】:
                  SimpleDateFormat sdf=new SimpleDateFormat("d/MM/yyyy");
                  Date date=null;
                  Date date1=null;
                  try {
                         date=sdf.parse(startDate);
                         date1=sdf.parse(endDate);
                      }  catch (ParseException e) {
                                e.printStackTrace();
                      }
                  if (date1.after(date) && date1.equals(date)) {
                  //..do your work..//
                  }
                  

                  【讨论】:

                    【解决方案15】:

                    Kotlin 支持运算符重载

                    在 Kotlin 中,您可以使用比较运算符轻松比较日期。因为 Kotlin 已经支持运算符重载。 所以比较日期对象:

                    firstDate: Date = // your first date
                    secondDate: Date = // your second date
                    
                    if(firstDate < secondDate){
                    // fist date is before second date
                    }
                    
                    

                    如果您使用日历对象,您可以像这样轻松比较:

                    if(cal1.time < cal2.time){
                    // cal1 date is before cal2 date
                    }
                    

                    【讨论】:

                      【解决方案16】:

                      在 Kotlin 中,使用内置函数 after() 或 before() 来比较两个时间对象非常简单:

                      expirationTime.after(Date())
                      

                      【讨论】:

                        猜你喜欢
                        • 1970-01-01
                        • 1970-01-01
                        • 2017-10-30
                        • 2016-03-07
                        • 1970-01-01
                        • 2015-03-26
                        • 2013-02-26
                        • 2012-03-07
                        • 1970-01-01
                        相关资源
                        最近更新 更多