【问题标题】:How to compare time string with current time in java?如何在java中将时间字符串与当前时间进行比较?
【发布时间】:2014-07-24 07:37:00
【问题描述】:

我有一个像“15:30”这样的时间字符串,我想将该字符串与当前时间进行比较。 请推荐一些简单的东西。 以及如何以小时分钟格式获取当前时间("HH:mm")

【问题讨论】:

  • 你想要一个“现在”的范围吗?例如在“12:34.999”,12:34 是匹配的,但 1 毫秒后它不是 - 这就是你想要的吗?
  • 我只是想比较一下当前时间是否大于时间字符串。
  • 这是我要比较的时间字符串。字符串 time1End = Integer.toString(calendar.get(Calendar.HOUR_OF_DAY)) + ":15";我将其转换为以下格式。 java.util.Date endTime1 = new SimpleDateFormat("HH:mm").parse(time1End);现在将 sstemdate 转换为上述时间格式。 java.util.Date systemdate = new java.util.Date(); SimpleDateFormat 解析器 = new SimpleDateFormat("HH:mm"); String systemTime = parser.format(systemdate); java.util.Date currentTime = new SimpleDateFormat("HH:mm").parse(systemTime);然后我们可以这样比较。 if (currentTime.after(endTime1))

标签: java datetime comparison


【解决方案1】:

tl;博士

LocalTime.now()
         .isAfter( LocalTime.parse( "15:30" ) )

详情

你应该反过来想:如何把那个字符串变成一个时间值。您不会通过将数字转换为字符串来尝试数学。日期时间值也是如此。

避免使用旧的捆绑类 java.util.Date 和 .Calendar,因为它们出了名的麻烦,在设计和实现上都有缺陷。它们被Java 8 中的新java.time package 取代。而 java.time 的灵感来自 Joda-Time

java.timeJoda-Time 都提供了一个类来捕获没有任何日期到时区的时间:LocalTime

java.time

使用 Java 中内置的 java.time 类,特别是 LocalTime。获取您当地时区的当前时间。根据您的输入字符串构造一个时间。与isBeforeisAfterisEqual 方法进行比较。

LocalTime now = LocalTime.now();
LocalTime limit = LocalTime.parse( "15:30" );
Boolean isLate = now.isAfter( limit );

最好指定您想要/预期的时区,而不是隐式依赖 JVM 当前的默认时区。

ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
LocalTime now = LocalTime.now( z );  // Explicitly specify the desired/expected time zone.
LocalTime limit = LocalTime.parse( "15:30" );
Boolean isLate = now.isAfter( limit );

乔达时间

本例中使用 Joda-Time 库的代码恰好与上面看到的 java.time 代码几乎相同。

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


关于java.time

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

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

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

从哪里获得 java.time 类?

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

【讨论】:

  • 感谢回复,我用的是java 6,能否提供java 6的相同解决方案
  • @mayanksharma Joda-Time 2.3 适用于 Java 5、6、7 和 8。只需将 the jar file 添加到您的项目中。
  • @mayanksharma 更新:Joda-Time 项目现在处于维护模式。该团队建议迁移到 java.time 类。对于 Java 6 和 7,您会在 ThreeTen-Backport 项目中找到向后移植的大部分 java.time 功能。对于 Android,ThreeTenABP。
【解决方案2】:

像这样正常比较字符串:

String currentTime = new SimpleDateFormat("HH:mm").format(new Date());
String timeToCompare = "15:30";
boolean x = currentTime.equals(timeToCompare);

如果时间相同,x 将是true,如果它们不同,x 将是false

【讨论】:

    【解决方案3】:

    以下将获得时间。你可以用它来比较

    String currentTime=new SimpleDateFormat("HH:mm").format(new Date());
    

    【讨论】:

      【解决方案4】:

      我有类似的情况,我需要将“15:30”之类的时间字符串与当前时间进行比较。 我正在使用 Java 7,所以我不能使用 Basil Bourque 的解决方案。 所以我实现了一种方法,它采用一个字符串,如 "15:30" 和 检查当前时间,如果当前时间晚于输入时间,则返回 true

      public static boolean checkSlaMissedOrNot(String sla) throws ParseException {
              boolean slaMissedOrnot = false;
              Calendar cal = Calendar.getInstance();
              cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(sla.substring(0, 2)));
              cal.set(Calendar.MINUTE, Integer.parseInt(sla.substring(3)));
              cal.set(Calendar.SECOND, 0);
              cal.set(Calendar.MILLISECOND, 0);
              if (Calendar.getInstance().after(cal)) {
                  System.out.println("it's SLA missed");
                  slaMissedOrnot = true;
              } else {
                  System.out.println("it's fine & not SLA missed");
              }
              return slaMissedOrnot;
          }
      

      日历还有其他使用完整的方法,例如after(Object when)

      返回此日历是否表示指定对象表示的时间之后的时间。 您也可以使用此方法将时间字符串与当前时间进行比较。

      【讨论】:

        【解决方案5】:

        所以我的解决方案有点不同,它首先创建一个具有当前时间的时钟,然后根据用户定义的 int 测试小时。

            public void TextClockWindow() {
        
            this.pack();
        
            javax.swing.Timer t = new javax.swing.Timer(1000, (ActionEvent e) -> {
                Calendar calendar = new GregorianCalendar();
                String am_pm;
                calendar.setTimeZone(TimeZone.getDefault());
        
                Calendar now = Calendar.getInstance();
                int h = now.get(Calendar.HOUR_OF_DAY);
                int m = now.get(Calendar.MINUTE);
                int s = now.get(Calendar.SECOND);
        
                if (calendar.get(Calendar.AM_PM) == 0) {
                    am_pm = "AM";
        
                } else {
                    am_pm = "PM";
        
                }   // Code to Determine whether the time is AM or PM
        
                Clock.setText("" + h + ":" + m + " " + am_pm);
        
                if(h < 5) { //int here which tests agaisnt the hour evwery second
                System.out.println("Success");
                } else {
                System.out.println("Failure"); 
                }
            });
            t.start();
        }
        

        【讨论】:

          【解决方案6】:

          试试这个

          public static String compareTime(String d) {
                  if (null == d)
                      return "";
          
                  try {
          
                      SimpleDateFormat sdf= new SimpleDateFormat("HH:mm");
                      d = sdf.format(new Date());
                  } catch (Exception e) {
                      e.printStackTrace();
          
                  }
          
                  return d;
          
              }
          

          然后您可以与您的字符串进行比较

          【讨论】:

            【解决方案7】:

            这是我比较当前时间前后的示例:

            MainActivity.java

            Button search = (Button) findViewById(R.id.searchBus);
                    SimpleDateFormat sdfDate = new SimpleDateFormat("HH:mm");
            
                    String limit = "23:00";
                    Date limitBus=null;
                    try {
                        limitBus = sdfDate.parse(limit);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
            
                    String start = "07:15";
                    Date startBus=null;
                    try {
                        startBus = sdfDate.parse(start);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
            
                    String user_time = getCurrentTimeStamp();
                    Date now = null;
                    try {
                        now = sdfDate.parse(user_time);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
            
                    if (now.after(limitBus)||now.before(startBus)){
                        Toast.makeText(this, "Bus Operation Hours : 7:15AM - 11.00PM", Toast.LENGTH_LONG).show();
                        search.setEnabled(false);
                    }
            
                    else
                    {
                        search.setEnabled(true);
                    }
            
            
            
            //get current time method
             public static String getCurrentTimeStamp() {
                    SimpleDateFormat sdfDate = new SimpleDateFormat("HH:mm");//dd/MM/yyyy
                    Date now = new Date();
                    String strDate = sdfDate.format(now);
                    return strDate;
                }
            

            【讨论】:

              【解决方案8】:

              此代码将检查用户输入时间当前系统时间,并将返回时差长值。

              public long getTimeDifferenceInMillis (String dateTime) {
              
                      SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
              
                      long currentTime = new Date().getTime();
                      long endTime = 0;
              
                      try {
                          //Parsing the user Inputed time ("yyyy-MM-dd HH:mm:ss")
                          endTime = dateFormat.parse(dateTime).getTime(); 
                      } catch (ParseException e) {
                          e.printStackTrace();
                          return 0;
                      }
              
                      if (endTime > currentTime)
                          return endTime - currentTime;
                      else
                          return 0;
                  }
              

              用户应该以"yyyy-MM-dd HH:mm:ss"格式打发时间。

              【讨论】:

              • 请不要教年轻人使用早已过时且臭名昭著的SimpleDateFormat类。至少不是第一选择。而且不是没有任何保留。今天我们在java.time, the modern Java date and time API 和它的DateTimeFormatter 中做得更好。
              猜你喜欢
              • 1970-01-01
              • 2022-09-27
              • 1970-01-01
              • 1970-01-01
              • 2022-01-16
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2013-12-24
              相关资源
              最近更新 更多