calculate Days Between LocalDateTime - Java java.time

Java examples for java.time:LocalDateTime

Description

calculate Days Between LocalDateTime

Demo Code


//package com.java2s;

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

public class Main {
    private static final long DAY = 86400;

    public static double calculateDaysBetweenLocalDateTime(
            LocalDateTime fromDateTime, LocalDateTime toDateTime) {
        return calculateSecondsBetweenLocalDateTime(fromDateTime,
                toDateTime) / ((double) DAY);
    }/*ww  w . ja  v a 2 s  . c om*/

    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