Java TimeUnit Usage parseDuration(String text)

Here you can find the source of parseDuration(String text)

Description

parse Duration

License

Open Source License

Declaration

public static long parseDuration(String text) 

Method Source Code

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

import java.util.concurrent.TimeUnit;

public class Main {
    public static long parseDuration(String text) {
        // Given a string like 1w3d4h5m, we will return a millisecond duration
        long result = 0;
        int numIdx = 0;
        for (int i = 0; i < text.length(); i++) {
            char at = text.charAt(i);
            if (at == 'd' || at == 'w' || at == 'm' || at == 'h') {
                String ns = text.substring(numIdx, i);
                numIdx = i + 1;/*www . j  av  a 2 s  .  c  o  m*/

                if (ns.isEmpty()) {
                    continue;
                }

                int n = Integer.parseInt(ns);
                switch (at) {
                case 'd':
                    result += TimeUnit.DAYS.toMillis(n);
                    break;
                case 'w':
                    result += TimeUnit.DAYS.toMillis(n * 7);
                    break;
                case 'h':
                    result += TimeUnit.HOURS.toMillis(n);
                    break;
                case 'm':
                    result += TimeUnit.MINUTES.toMillis(n);
                    break;
                }
            } else if (!Character.isDigit(at)) {
                throw new IllegalArgumentException("Character " + at + " in position " + (i + 1) + " not valid");
            }
        }

        return result;
    }
}

Related

  1. nanoToString(final long nanos)
  2. now()
  3. numberOfDaysSinceEpoch(long milliSinceEpoch)
  4. parseDate(String value)
  5. parseDuration(String durationStr)
  6. parseRelativeTimeInSeconds(String relativeTime)
  7. parseSecondsFromEpoch(Double d)
  8. parseStringDate(String date)
  9. parseTimeMillis(String timeWithOrWithoutUnit)