Java Duration Create getDuration(Object o, TemporalUnit unit)

Here you can find the source of getDuration(Object o, TemporalUnit unit)

Description

get Duration

License

Open Source License

Declaration

public static Duration getDuration(Object o, TemporalUnit unit) 

Method Source Code

//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

import java.time.Duration;
import java.time.temporal.TemporalUnit;

public class Main {
    public static Duration getDuration(Object o, TemporalUnit unit) {
        if (o != null && o instanceof Duration) {
            return (Duration) o;
        }/* www  .jav  a 2s. c o  m*/
        try {
            return Duration.of(getLong(o), unit);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("Don't know how to convert " + o + " to Duration", e);
        }
    }

    public static Long getLong(Object o) {
        if (o instanceof Long) {
            return (Long) o;
        } else if (o instanceof Integer) {
            return ((Integer) o).longValue();
        } else if (o instanceof Short) {
            return ((Short) o).longValue();
        } else {
            try {
                return Long.parseLong(o.toString());
            } catch (NumberFormatException nfe) {
                throw new IllegalArgumentException("Don't know how to convert " + o + " to long");
            }
        }
    }
}

Related

  1. getDuration(final Date started, final Date finished)