Java Duration to toUnit(TemporalUnit unit, Duration duration)

Here you can find the source of toUnit(TemporalUnit unit, Duration duration)

Description

to Unit

License

Open Source License

Declaration

public static long toUnit(TemporalUnit unit, Duration duration) 

Method Source Code


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

import java.time.Duration;

import java.time.temporal.ChronoUnit;

import java.time.temporal.TemporalUnit;

public class Main {
    public static long toUnit(TemporalUnit unit, Duration duration) {
        switch ((ChronoUnit) unit) {
        case NANOS:
            return duration.toNanos();
        case MICROS:
            return toMicros(duration);
        case MILLIS:
            return duration.toMillis();
        case SECONDS:
            return duration.getSeconds();
        }//from  ww  w .  j  a  v a  2s .  c  om

        if (unit.getDuration().getNano() == 0) {
            return duration.getSeconds() / unit.getDuration().getSeconds();
        }

        throw new IllegalArgumentException("Unsupported sub-second unit " + unit);
    }

    public static long toMicros(Duration duration) {
        return Math.addExact(Math.multiplyExact(duration.getSeconds(), 1_000_000), duration.getNano() / 1_000);
    }
}

Related

  1. toDuration(Long unixTime)
  2. toDuration(String durationString)
  3. toMicro(Duration duration)
  4. toSeconds(final Duration time)
  5. toTicks(Duration duration)