Example usage for java.time.temporal ChronoUnit between

List of usage examples for java.time.temporal ChronoUnit between

Introduction

In this page you can find the example usage for java.time.temporal ChronoUnit between.

Prototype

@Override
    public long between(Temporal temporal1Inclusive, Temporal temporal2Exclusive) 

Source Link

Usage

From source file:org.talend.dataprep.transformation.actions.date.ComputeTimeSinceTest.java

/**
 * Compute time since .//from   ww  w.  ja  v  a2 s.  com
 *
 * @param date      the date to compute from.
 * @param pattern   the pattern to use.
 * @param unit      the unit for the result.
 * @param sinceWhen the date to calculate since when
 * @return time since now in the wanted unit.
 */
String computeTimeSince(String date, String pattern, ChronoUnit unit, String sinceWhen) {

    DateTimeFormatter format = DateTimeFormatter.ofPattern(pattern);
    Temporal since;
    if (sinceWhen == null) {
        since = LocalDateTime.now();
    } else {
        since = LocalDateTime.parse(sinceWhen, format);
    }

    LocalDateTime start;
    try {
        start = LocalDateTime.parse(date, format);
    } catch (Exception e) {
        start = null;
    }

    if (start == null) {
        LocalDate temp = LocalDate.parse(date, format);
        start = temp.atStartOfDay();
    }

    Temporal result = LocalDateTime.from(start);
    return String.valueOf(unit.between(result, since));
}