【问题标题】:Convert time field H:M into integer field (minutes) in JAVA将时间字段 H:M 转换为 JAVA 中的整数字段(分钟)
【发布时间】:2012-01-18 11:10:10
【问题描述】:

JTable 包含时间字段,例如“01:50”。我需要将此值读入整数变量。为此,我想将时间转换为分钟。例如“01:50”应该转换成110。

为了解决这个任务,我首先将时间值保存为字符串。

String minutS = tableModel.getValueAt(1,1).toString();

其次,我将处理这个字符串并提取符号: 前后的整数。最后我会计算总分钟数。 这个解决方案有效吗?也许,可以用日历或类似的东西代替它?

【问题讨论】:

  • 表模型中数据的实际类型是什么?

标签: java swing time


【解决方案1】:

对于这种情况,我认为使用日历/日期不会比直接解析更好。如果您的时间格式确实是 H:m,那么我认为您不需要比这更复杂的东西:

/**
 * @param s H:m timestamp, i.e. [Hour in day (0-23)]:[Minute in hour (0-59)]
 * @return total minutes after 00:00
 */
private static int toMins(String s) {
    String[] hourMin = s.split(":");
    int hour = Integer.parseInt(hourMin[0]);
    int mins = Integer.parseInt(hourMin[1]);
    int hoursInMins = hour * 60;
    return hoursInMins + mins;
}

【讨论】:

  • @sudocode如果给定的字符串是 12 小时格式,比如下午 3:30,上面的代码会出现问题,那么上面的代码将在行上抛出 numberFormat 异常: int mins = Integer.parseInt(hourMin[1]);那么如何用上面的代码避免这个问题呢?所以基本上字符串可以是 12 小时格式或 24 小时格式它应该可以工作!!!!!!
【解决方案2】:

查看下面我们在应用程序中使用的示例

public static int toMinutes( String sDur, boolean bAssumeMinutes ) throws NumberFormatException {
        /* Use of regular expressions might be better */
        int iMin = 0;
        int iHr = 0;
        sDur = sDur.trim();
        //find punctuation
        int i = sDur.indexOf(":");//HH:MM
        if (i < 0) {
            //no punctuation, so assume whole thing is an number
            //double dVal = Double.parseDouble(sDur);
            double dVal = ParseAndBuild.parseDouble(sDur, Double.NaN);
            if (Double.isNaN(dVal)) throw new NumberFormatException(sDur);
            if (!bAssumeMinutes) {
                //decimal hours so add half a minute then truncate to minutes
                iMin = (int)((dVal * 60.0) + (dVal < 0 ? -0.5 : 0.5));
            } else {
                iMin = (int)dVal;
            }
        }
        else {
            StringBuffer sBuf = new StringBuffer(sDur);
            int j = sBuf.indexOf(MINUS_SIGN);
            //check for negative sign
            if (j >= 0) {
                //sign must be leading/trailing but either allowed regardless of MINUS_SIGN_TRAILS
                if (j > 0 && j < sBuf.length() -1)
                    throw new NumberFormatException(sDur);                  
                sBuf.deleteCharAt(j);
                i = sBuf.indexOf(String.valueOf(":"));
            }
            if (i > 0)
                iHr = Integer.parseInt(sBuf.substring(0, i)); //no thousands separators allowed
            if (i < sBuf.length() - 1)
                iMin = Integer.parseInt(sBuf.substring(i+1));
            if (iMin < 0 || (iHr != 0 && iMin >= 60))
                throw new NumberFormatException(sDur);
            iMin += iHr * 60;
            if (j >= 0) iMin = -iMin;
        }
        return iMin;
    }

【讨论】:

    【解决方案3】:

    这个怎么样:

    String time = "1:50";
    String[] split = time.split(":"); 
    if(split.length == 2) { 
            long minutes = TimeUnit.HOURS.toMinutes(Integer.parseInt(split[0])) + 
                             Integer.parseInt(split[1]);
            System.out.println(minutes);
        }
    
    /* Output: 110 */
    

    【讨论】:

      【解决方案4】:

      在处理之前剥离您的输入。 (commons-lang utils)

      空格可以使NumberFormatExceptions出现。

      【讨论】:

        【解决方案5】:

        从 java 1.8 开始,最优雅的解决方案可能是:

        long minutes = ChronoUnit.MINUTES.between(LocalTime.MIDNIGHT, LocalTime.parse("01:50"));

        【讨论】:

          【解决方案6】:

          SudoCode 的回答帮助我找到了答案,不过我对我的方法所做的一个补充是添加逻辑来处理字符串输入是否也有几天的字段。 (我的场景是处理经过的时间)。

          我添加了一个 if 语句来处理从天数中获取分钟的逻辑,然后我覆盖了输入字符串变量以保存原始字符串的其余部分。

          此方法的预期格式应为 110 天 09:38:45.749298 ...

              private long convertElapsedTimeToMinutes(String elapsedTimeString) {
          
                  long daysInMinutes              =   0;
                  long hoursInMinutes             =   0;
                  long minutes                    =   0;
          
                  if(elapsedTimeString.contains("days")) {
                      String[] daySplitStrings    =   elapsedTimeString.split("days");
                      daysInMinutes               =   Long.parseLong(daySplitStrings[0].trim())*24*60;
                      elapsedTimeString           =   daySplitStrings[1];
                  }
          
                  String[] hourMinuteSplitStrings =   elapsedTimeString.split(":");
                  hoursInMinutes                  =   Long.parseLong(hourMinuteSplitStrings[0].trim()) * 60;
                  minutes                         =   Long.parseLong(hourMinuteSplitStrings[0].trim());
          
                  return daysInMinutes + hoursInMinutes + minutes;
              }
          

          【讨论】:

            猜你喜欢
            • 2019-11-16
            • 2013-04-10
            • 2021-02-10
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-05-06
            相关资源
            最近更新 更多