Java Duration to toDuration(String durationString)

Here you can find the source of toDuration(String durationString)

Description

to Duration

License

Apache License

Declaration

public static Duration toDuration(String durationString) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.time.Duration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    private static final Pattern DUR_PAT = Pattern.compile("(\\d+)(\\s?(?:d|h|ms?|s))");

    public static Duration toDuration(String durationString) {
        Duration dur = Duration.ZERO;
        Matcher match = DUR_PAT.matcher(durationString);
        while (match.find()) {
            long amount = Long.parseLong(match.group(1));
            switch (match.group(2)) {
            case "d":
                dur = dur.plusDays(amount);
                break;
            case "h":
                dur = dur.plusHours(amount);
                break;
            case "m":
                dur = dur.plusMinutes(amount);
                break;
            case "s":
                dur = dur.plusSeconds(amount);
                break;
            case "ms":
                dur = dur.plusNanos(amount * 1000000L);
                break;
            }/*w w  w .j  a v  a2 s .  c  o  m*/
        }
        return dur;
    }

    public static Duration toDuration(long timeInMillis) {
        return Duration.ofMillis(timeInMillis);
    }
}

Related

  1. durationToFloat(Duration duration)
  2. durationToString(Duration d)
  3. toDuration(Long unixTime)
  4. toMicro(Duration duration)
  5. toSeconds(final Duration time)
  6. toTicks(Duration duration)
  7. toUnit(TemporalUnit unit, Duration duration)