7

98d 01h 23m 45s形式の期間文字列をミリ秒単位で解析する必要があります。

このような期間に相当するものがあることを望んでいましたが、SimpleDateFormat何も見つかりませんでした。この目的で SDF を使用することを推奨または反対する人はいますか?

私の現在の計画は、正規表現を使用して数値と照合し、次のようなことを行うことです

Pattern p = Pattern.compile("(\\d+)");
Matcher m = p.matcher("98d 01h 23m 45s");

if (m.find()) {
    int days = Integer.parseInt(m.group());
}
// etc. for hours, minutes, seconds

次に、TimeUnitを使用してすべてをまとめ、ミリ秒に変換します。

私の質問は、これはやり過ぎのように思えますが、もっと簡単にできるでしょうか? 日付とタイムスタンプに関する多くの質問が寄せられましたが、これは少し違うかもしれません。

4

4 に答える 4

11

JodaTime ライブラリからチェックアウトしPeriodFormatterます。PeriodParser

PeriodFormatterBuilderこのような文字列のパーサーを構築するために使用することもできます

String periodString = "98d 01h 23m 45s";

PeriodParser parser = new PeriodFormatterBuilder()
   .appendDays().appendSuffix("d ")
   .appendHours().appendSuffix("h ")
   .appendMinutes().appendSuffix("m ")
   .appendSeconds().appendSuffix("s ")
   .toParser();

MutablePeriod period = new MutablePeriod();
parser.parseInto(period, periodString, 0, Locale.getDefault());

long millis = period.toDurationFrom(new DateTime(0)).getMillis();

さて、これらすべて (特にそのtoDurationFrom(...)部分) は扱いにくいように見えるかもしれませんがJodaTime、Java でピリオドとデュレーションを扱っている場合は、調べてみることを強くお勧めします。

さらに明確にするために、JodaTime 期間からミリ秒を取得することに関するこの回答も参照してください。

于 2012-06-13T19:28:00.587 に答える
6

a を使用するのPatternが妥当な方法です。しかし、1 つのフィールドを使用して 4 つのフィールドすべてを取得してみませんか?

Pattern p = Pattern.compile("(\\d+)d\\s+(\\d+)h\\s+(\\d+)m\\s+(\\d+)s");

次に、インデックス付きグループ フェッチを使用します。

編集:

あなたのアイデアに基づいて、私は最終的に次の方法を書きました

private static Pattern p = Pattern
        .compile("(\\d+)d\\s+(\\d+)h\\s+(\\d+)m\\s+(\\d+)s");

/**
 * Parses a duration string of the form "98d 01h 23m 45s" into milliseconds.
 * 
 * @throws ParseException
 */
public static long parseDuration(String duration) throws ParseException {
    Matcher m = p.matcher(duration);

    long milliseconds = 0;

    if (m.find() && m.groupCount() == 4) {
        int days = Integer.parseInt(m.group(1));
        milliseconds += TimeUnit.MILLISECONDS.convert(days, TimeUnit.DAYS);
        int hours = Integer.parseInt(m.group(2));
        milliseconds += TimeUnit.MILLISECONDS
                .convert(hours, TimeUnit.HOURS);
        int minutes = Integer.parseInt(m.group(3));
        milliseconds += TimeUnit.MILLISECONDS.convert(minutes,
                TimeUnit.MINUTES);
        int seconds = Integer.parseInt(m.group(4));
        milliseconds += TimeUnit.MILLISECONDS.convert(seconds,
                TimeUnit.SECONDS);
    } else {
        throw new ParseException("Cannot parse duration " + duration, 0);
    }

    return milliseconds;
}
于 2012-06-13T19:29:26.407 に答える
4

Java 8の新しいjava.time.Durationクラスを使用すると、すぐに期間を解析できます。

Duration.parse("P98DT01H23M45S").toMillis();

形式が若干異なるため、解析する前に調整する必要があります。

于 2014-03-17T15:26:19.457 に答える