簡體   English   中英

將小時,分鍾,秒字符串轉換為小時

[英]Convert hours, mins, secs String to hours

我想將以下格式的時間轉換為幾小時。

我輸入的時間格式可能就像

1 hour 30 mins 20 secs 
2 hrs 10 mins 
45 mins 

而我的輸出將是:

1.505
2.167
0.75

這些是時間。

目前我通過解析輸入字符串1 hour 30 mins 20 secs來手動完成,查找單詞hour/hours/hrs/hr是否存在,然后取出前面的數字 - 相同的分鍾和秒。 我使用公式手動將分鍾和秒轉換為小時。

是否有可以在Java中使用的內置規定?

另一種方法是將其解析為Duration ,但您需要先改變格式。 就像是:

String adjusted = input.replaceAll("\\s+(hour|hr)[s]\\s+", "H");
//Do the same for minutes and seconds
//So adjusted looks like 1H30M20S
Duration d = Duration.parse("PT" + adjusted);

double result = d.toMillis() / 3_600_000d;

通常我不會推薦Joda-Time (因為它被新的Java API替換),但它是我所知道的唯一一個具有良好格式化程序/解析器的API。

您可以使用PeriodFormatterBuilder類並使用appendSuffix方法為每個字段定義單數和復數值的后綴:

import org.joda.time.Period;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;

// method to parse the period
public void getPeriod(String input) {
    PeriodFormatter formatter = new PeriodFormatterBuilder()
            // hours (singular and plural suffixes)
            .appendHours().appendSuffix("hour", "hours")
            // minutes
            .appendMinutes().appendSuffix("min", "mins")
            // seconds
            .appendSeconds().appendSuffix("sec", "secs")
            // create formatter
            .toFormatter();

    // remove spaces and change "hr" to "hour"
    Period p = formatter.parsePeriod(input.replaceAll(" ", "").replaceAll("hr", "hour")); 

    double hours = p.getHours();
    hours += p.getMinutes() / 60d;
    hours += p.getSeconds() / 3600d;
    System.out.println(hours);
}

// tests
getPeriod("1 hour 30 mins 20 secs");
getPeriod("2 hrs 10 mins");
getPeriod("45 mins");

輸出:

1.5055555555555555
2.1666666666666665
0.75


創建PeriodFormatter另一種方法是使用帶正則表達式的appendSuffix 當你有很多不同的后綴選項時(例如小時字段的hourhr ,它很有用:

PeriodFormatter formatter = new PeriodFormatterBuilder()
    // hours (all possible suffixes for singular and plural)
    .appendHours()
    .appendSuffix(
        // regular expressions for singular and plural
        new String[] { "^1$", ".*", "^1$", ".*" },
        // possible suffixes for singular and plural
        new String[] { " hour", " hours", " hr", " hrs" })
    // optional space (if there are more fields)
    .appendSeparatorIfFieldsBefore(" ")
    // minutes
    .appendMinutes().appendSuffix(" min", " mins")
    // optional space (if there are more fields)
    .appendSeparatorIfFieldsBefore(" ")
    // seconds
    .appendSeconds().appendSuffix(" sec", " secs")
    // create formatter
    .toFormatter();

請注意,我還添加了appendSeparatorIfFieldsBefore(" ")以指示它在下一個字段之前有空格。

這個版本的好處是你不需要預處理輸入:

// no need to call replaceAll (take input just as it is)
Period p = formatter.parsePeriod(input);

輸出與上面相同。


Java 8日期時間API

@ assylian的回答所述 ,您可以使用java.time.Duration類:

public void getDuration(String input) {
    // replace hour/min/secs strings for H, M and S
    String adjusted = input.replaceAll("\\s*(hour|hr)s?\\s*", "H");
    adjusted = adjusted.replaceAll("\\s*mins?\\s*", "M");
    adjusted = adjusted.replaceAll("\\s*secs?\\s*", "S");
    Duration d = Duration.parse("PT" + adjusted);

    double hours = d.toMillis() / 3600000d;
    System.out.println(hours);
}

//tests
getDuration("1 hour 30 mins 20 secs");
getDuration("2 hrs 10 mins");
getDuration("45 mins");

輸出是一樣的。

PS:如果你的Java版本<= 7,你可以使用ThreeTen Backport 類名和方法是相同的,唯一的區別是包名: org.threeten.bp而不是java.time

目前我這樣做:

private double convertToHours(String inputTime) {
    inputTime = " 1 hour 30 mins 20 secs";
    double hours = 0;
    List<String> timeList = Arrays.asList(inputTime.split(" "));
    ListIterator<String> iterator = timeList.listIterator();
    String time = null;
    String previous = null;
    while (iterator.hasNext()) {
        int prevIndex = iterator.previousIndex();
        time = (String) iterator.next();

        if (!time.isEmpty() && time != null) {

            if (time.contains("hours") || time.contains("hrs") || time.contains("hr") || time.contains("hour")) {
                // time = time.substring(0, time.indexOf('h'));
                    previous = timeList.get(prevIndex);

                hours = hours + Double.parseDouble(previous.trim());
            }

            if (time.contains("mins") || time.contains("min") || time.contains("mns")) {
                //time = time.substring(0, time.indexOf('m'));
                previous = timeList.get(prevIndex);
                hours = hours + Double.parseDouble(previous) / 60;
            }

            if (time.contains("secs") || time.contains("sec") || time.contains("scs")) {
                //time = time.substring(0, time.indexOf('s'));
                previous = timeList.get(prevIndex);
                hours = hours + Double.parseDouble(previous) / 3600;
            }
        }
    }
    return hours;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM