Java Duration Create getDuration(final Date started, final Date finished)

Here you can find the source of getDuration(final Date started, final Date finished)

Description

Get the duration between when something was started and finished.

License

Open Source License

Parameter

Parameter Description
started The start time. Can be null will automatically set the duration to 0
finished The finish time. If null will use (current time - started time) to get the duration

Return

The duration or zero if no duration

Declaration

public static Duration getDuration(final Date started, final Date finished) 

Method Source Code


//package com.java2s;
import java.time.Duration;
import java.util.Date;

public class Main {
    /**//from w  w w  . j a v  a  2 s  .c  o  m
     * Get the duration between when something was started and finished.
     *
     * @param started The start time. Can be null will automatically set the duration to 0
     * @param finished The finish time. If null will use (current time - started time) to get the
     *        duration
     * @return The duration or zero if no duration
     */
    public static Duration getDuration(final Date started, final Date finished) {

        if (started == null || started.getTime() == 0) {
            // Never started
            return Duration.ZERO;
        } else if (finished == null || finished.getTime() == 0) {
            // Started but hasn't finished
            return Duration.ofMillis(new Date().getTime() - started.getTime());

        } else {
            // Started and finished
            return Duration.ofMillis(finished.getTime() - started.getTime());
        }
    }
}

Related

  1. getDuration(Object o, TemporalUnit unit)