calculate Hours Between LocalDateTime - Java java.time

Java examples for java.time:LocalDateTime

Description

calculate Hours Between LocalDateTime

Demo Code


//package com.java2s;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

public class Main {
    private static final long HOUR = 3600;

    public static double calculateHoursBetweenLocalDateTime(
            LocalDateTime fromDateTime, LocalDateTime toDateTime) {
        return calculateSecondsBetweenLocalDateTime(fromDateTime,
                toDateTime) / ((double) HOUR);
    }/*from w w w  . j  a v a  2 s.  co m*/

    public static long calculateSecondsBetweenLocalDateTime(
            LocalDateTime fromDateTime, LocalDateTime toDateTime) {
        LocalDateTime tempDateTime = LocalDateTime.from(fromDateTime);
        long years = tempDateTime.until(toDateTime, ChronoUnit.YEARS);
        tempDateTime = tempDateTime.plusYears(years);
        long months = tempDateTime.until(toDateTime, ChronoUnit.MONTHS);
        tempDateTime = tempDateTime.plusMonths(months);
        long days = tempDateTime.until(toDateTime, ChronoUnit.DAYS);
        tempDateTime = tempDateTime.plusDays(days);
        long hours = tempDateTime.until(toDateTime, ChronoUnit.HOURS);
        tempDateTime = tempDateTime.plusHours(hours);
        long minutes = tempDateTime.until(toDateTime, ChronoUnit.MINUTES);
        tempDateTime = tempDateTime.plusMinutes(minutes);
        long seconds = tempDateTime.until(toDateTime, ChronoUnit.SECONDS);
        //do some addition
        return 0 + Math.round(((double) years) * 31556900d)
                + Math.round(((double) months) * 2629740d)
                + Math.round(((double) days) * 86400d)
                + Math.round(((double) hours) * 3600d)
                + Math.round(((double) minutes) * 60d)
                + Math.round(((double) seconds));
    }
}

Related Tutorials