Java Duration Parse parseDurationString(String time)

Here you can find the source of parseDurationString(String time)

Description

parse Duration String

License

Open Source License

Declaration

public static Duration parseDurationString(String time) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.time.Duration;

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

public class Main {
    public static Duration parseDurationString(String time) {

        Pattern timePattern = Pattern.compile("[1-9][0-9]*(y|mo|w|h|d|m|s)");
        Matcher matcher = timePattern.matcher(time);
        int years = 0;
        int months = 0;
        int weeks = 0;
        int days = 0;
        int hours = 0;
        int minutes = 0;
        int seconds = 0;

        while (matcher.find()) {
            String r = matcher.group();
            switch (r.charAt(r.length() - 1)) {
            case 'y': {
                years = Integer.parseInt(r.replace("y", ""));
                break;
            }//from w w w  .j  a va 2  s. c  om
            case 'o': {
                months = Integer.parseInt(r.replace("mo", ""));
                break;
            }
            case 'w': {
                weeks = Integer.parseInt(r.replace("w", ""));
                break;
            }
            case 'd': {
                days = Integer.parseInt(r.replace("d", ""));
                break;
            }
            case 'h': {
                hours = Integer.parseInt(r.replace("h", ""));
                break;
            }
            case 'm': {
                minutes = Integer.parseInt(r.replace("m", ""));
                break;
            }
            case 's': {
                seconds = Integer.parseInt(r.replace("s", ""));
                break;
            }

            }
        }
        return Duration.ofDays(years * 365 + months * 30 + weeks * 7 + days).plusHours(hours).plusMinutes(minutes)
                .plusSeconds(seconds);
    }
}

Related

  1. parseDuration(final Duration duration)
  2. parseDuration(String datePattern)