简体   繁体   English

格式化整数并将其转换为分钟和秒

[英]Format and convert integer number to minutes and seconds

In my Java application we have a text field where users enter numbers and we need to parse that number properly to format it to minutes and seconds.在我的 Java 应用程序中,我们有一个文本字段,用户可以在其中输入数字,我们需要正确解析该数字以将其格式化为分钟和秒。 Here is a table of possible values and what needs to be produced:以下是可能的值和需要生成的值的表格:

2     -> 02:00 OR 00:02
21    -> 00:21
215   -> 02:15
2157  -> 21:57

2:7   -> 02:07 OR 03:10
2:1   -> 02:01
2:71  -> 03:11
2:07  -> 02:07
20:7  -> 20:07 OR 21:10
20:61 -> 21:01

The OR parts I'm still thinking what should be the best way to do. OR部分我仍在思考什么应该是最好的方法。

I'm sure this problem before has been resolved before, I'm just looking for an already existing library that can handle this.我确定这个问题之前已经解决了,我只是在寻找一个可以处理这个问题的现有库。

Depending on what option you use you could do it by using standard java.time functionality根据您使用的选项,您可以使用标准的 java.time 功能来完成

LocalTime time = LocalTime.of(value / 100, value % 100);
String timeString = time.format(DateTimeFormatter.ofPattern("HH:mm"));

Example例子

for (int value : values) {
    LocalTime time = LocalTime.of(value / 100, value % 100);
    String timeString = time.format(DateTimeFormatter.ofPattern("HH:mm"));
    System.out.println(timeString);
}

00:02 00:02
00:21 00:21
02:15 02:15
21:57 21:57

Consider forbidding typing more than 59 seconds.考虑禁止输入超过 59 秒。 I doubt that users would have any reason to want to do that, so 2:71 is more likely a typo, and you can do the user a favour when you make them aware of that.我怀疑用户是否有任何理由想要这样做,因此 2:71 更有可能是一个错字,当您让他们意识到这一点时,您可以帮他们一个忙。 At least only allow it when no minutes are present.至少只有在没有分钟的时候才允许它。

RegEx and Duration正则表达式和持续时间

In any case, for the question as asked, one suggestion is to use a regular expression and the Duration class like this:无论如何,对于所问的问题,一个建议是使用正则表达式和Duration类,如下所示:

    Pattern durationPattern = Pattern.compile("(?:(\\d{1,2}?):?)??(\\d{1,2})");

    String[] inputs = { "2", "21", "215", "2157", "2:7",
            "2:1", "2:71", "2:07", "20:7", "20:61" };

    for (String input : inputs) {
        Matcher m = durationPattern.matcher(input);
        if (m.matches()) {
            String minuteStringOrNull = m.group(1);
            String secondString = m.group(2);
            Duration dur = minuteStringOrNull == null ? Duration.ZERO : Duration.ofMinutes(Integer.parseInt(minuteStringOrNull));
            dur = dur.plusSeconds(Integer.parseInt(secondString));

            String durationString = String.format("%02d:%02d", dur.toMinutes(), dur.toSecondsPart());

            System.out.format("%-5s -> %s%n", input, durationString);
        } else {
            System.out.println("Invalid input: " + input);
        }
    }

Output from this piece of code is:这段代码的输出是:

 2 -> 00:02 21 -> 00:21 215 -> 02:15 2157 -> 21:57 2:7 -> 02:07 2:1 -> 02:01 2:71 -> 03:11 2:07 -> 02:07 20:7 -> 20:07 20:61 -> 21:01

What I don't like about it myself is that the regular expression is so hard to read.我自己不喜欢它的是正则表达式很难阅读。 (?:(\\\\d{1,2}?):?) is a non-capturing group, (?:) works the same as brackets in math and programming. (?:(\\\\d{1,2}?):?)是一个非捕获组, (?: ... )与数学和编程中的括号相同。 And ??还有?? after it says that it may or not be there and take it reluctantly, that is, try without it first, then with.在它说它可能在或不在那里之后,不情愿地接受它,即先尝试无,然后有。 In this way, when there are few digits, we use them for seconds rather than minutes.这样,当数字很少时,我们将它们用于秒而不是分钟。 Inside the group (\\\\d{1,2}?) is a capturing group consisting of 1 or 2 digits (for minutes), again reluctant, prefer 1 over 2. :?在组内(\\\\d{1,2}?)是一个捕获组,由 1 或 2 位数字(分钟)组成,同样不情愿,更喜欢 1 而不是 2。 :? means that the 1 or two digits may or may not be followed by a colon.表示 1 或 2 位数字后面可以跟也可以不跟冒号。 Finally (\\\\d{1,2}) is another capturing group of 1 or 2 digits (for seconds).最后(\\\\d{1,2})是另一个 1 或 2 位数字(秒)的捕获组。 The capturing groups are what we take out using m.group() later in the code (they are numbered from 1).捕获组是我们稍后在代码中使用m.group()取出的m.group() (它们从 1 开始编号)。

If you end up deciding on other interpretations, you can probably modify the idea and/or the code accordingly.如果您最终决定其他解释,您可能可以相应地修改想法和/或代码。

More readable alternative更具可读性的替代方案

You may well prefer more easily readable code even when it's longer.即使代码更长,您也可能更喜欢更易于阅读的代码。 In this case hand parsing may be better than using a regular expression.在这种情况下,手动解析可能比使用正则表达式更好。 I believe you can build an algorithm along the following incomplete lines (not tested).我相信您可以按照以下不完整的行(未测试)构建算法。

    String[] parts = input.split(":", 3);
    if (parts.length == 1) { // no colon
        if (input.length > 2) {
            // take last two digits as seconds, everything else as minutes
        } else {
            // take everything as seconds
        }
    } else if (parts.length == 2) {
        // take minutes from parts[0] and seconds from parts[1]
    } else {
        // invalid input, too many colons
    }

Still use the Duration class as before.仍然像以前一样使用Duration类。

An existing library?现有的图书馆?

This is off-topic for Stack Overflow, but now we're at it: I don't know well enough to tell, but you may see whether Time4J or Joda-Time may help you here.这是 Stack Overflow 的题外话,但现在我们正在讨论:我不太清楚,但您可能会看到Time4JJoda-Time是否可以在这里帮助您。

Link关联

Documentation of regular expressions in Java Java 中的正则表达式文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Freemarker格式的整数,以分钟和秒为单位 - Freemarker format integer as minutes and seconds 如何将整数拆分为字符串并按秒/分钟/小时自动转换 - How to split an integer into String and Convert it automatically by seconds/minutes/hours 分钟和秒格式 - Minutes and seconds format 有人可以解释如何将大量秒数转换为可读的分钟和秒吗? - Can someone explain on how to convert huge number of seconds when getting to readable minutes and seconds? 将秒值转换为小时分钟秒? - Convert seconds value to hours minutes seconds? 如何通过java分别将数据库字段中的时间转换为integer的小时、分钟、秒? - how to convert the time from the database field into integer for hours, minutes, seconds separately through java? 将 LocalTime 分钟/秒格式化为 Integer Java - Formatting LocalTime Minutes/Seconds into Integer Java 需要以 int 形式计算分钟数,然后以 double 形式计算秒数。 方法应使用 Java 中的格式字符串 - Required to calculate the number of minutes as an int, then the seconds as a double. method should use a format string in Java 如何仅用分钟格式化 LocalDateTime(截断秒)? - How to format LocalDateTime with minutes only (truncate seconds)? 将毫秒转换为秒,分钟不四舍五入 - convert milliseconds to seconds, minutes without rounding
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM