Java duration between localdate

Calculate Seconds between two LocalDates in Java

i am trying to calculate seconds between two LocalDates. Now this is actually giving me a hard time as this code snippet is not working that well:

long seconds = lastRefreshPoint.until(systemTime, ChronoUnit.SECONDS); 
java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Minutes 

I cant really find any other way to do this on the Internet. It would be nice if you could help me! Thanks in advance

This does not make any sense since a calendar date does not know anything about hours, minutes or seconds. The lowest supported unit must be the day.

3 Answers 3

Okay, here my comment as answer together with some details about the reasons of the behaviour observed.

Summarizing:

This does not make any sense since a calendar date does not know anything about hours, minutes or seconds. The lowest supported unit must be the day. See also the API of Java-8-class LocalDate :

If the unit is a ChronoUnit then the query is implemented here. The supported units are: •DAYS •WEEKS •MONTHS •YEARS •DECADES •CENTURIES •MILLENNIA •ERAS All other ChronoUnit instances will return false.

While someone can imagine to implement the difference in seconds between two connecting days as 86400 seconds (ignoring zone effects or leap seconds), it would not be a good idea. If the API designers had decided to support the between-arithmetic then they should also have decided to support adding of seconds to a date. But here the problem starts:

Читайте также:  Youtube analytics api python

date + 86400 secs = next date

But what is date + 123 secs.

The support for units more precise than a day in the class LocalDate would cause inconsistencies which cannot be cured.

Источник

How to calculate time difference between two dates using LocalDateTime in Java 8?

There are numerous answers given but I am unable to find compatible with my situation. I need to find difference of 8 hours in time as well as on date change too. Like if time is greater then 8 hours then do not execute something . Do we have any method which achieve the same in LocalDateTime in Java-8? I have tried to use following but unable to achieve the same.

LocalDateTime fromDateTime = LocalDateTime.of(2017, 07, 07, 07, 00, 55); LocalDateTime toDateTime = LocalDateTime.now(); 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); System.out.println("" + java.time.Duration.between(tempDateTime, toDateTime).toHours()); System.out.println(years + " years " + months + " months " + days + " days " + hours + " hours " + minutes + " minutes " + seconds + " seconds."); 

It is difficult to check on time and date separately. Initially I coded it like but it does not looks correct:

2017 07 06 23:30:00 - 2017 07 07 01:30:00 - Should return 2 hours. 

Источник

Calculate days between two Dates in Java 8

If you want literal 24 hour days, (a duration), you can use the Duration class instead:

LocalDate today = LocalDate.now() LocalDate yesterday = today.minusDays(1); // Duration oneDay = Duration.between(today, yesterday); // throws an exception Duration.between(today.atStartOfDay(), yesterday.atStartOfDay()).toDays() // another option 

For more information, refer to this document: Java SE 8 Date and Time.

Читайте также:  How to copy file php

That throws an exception, because the Duration.between method requires temporal objects capable of supporting the SECONDS unit. Instead, try Duration.between(today.atTime(0, 0), yesterday.atTime(0, 0)).toDays() .

@REACHUS Maybe the -1 was a bit harsh because the code you propose works, but Duration is meant to measure «time-based amounts of time». There is a built-in way to measure a number of days which does not require converting from date to datetime.

The better answer for LocalDate’s is @Sunil B’s answer below: ChronoUnit.DAYS.between(firstDate, secondDate)

Based on VGR’s comments here is what you can use:

ChronoUnit.DAYS.between(firstDate, secondDate) 
LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4); LocalDate christmas = LocalDate.of(2014, Month.DECEMBER, 25); System.out.println("Until christmas: " + independenceDay.until(christmas)); System.out.println("Until christmas (with crono): " + independenceDay.until(christmas, ChronoUnit.DAYS)); 
Until christmas: P5M21D Until christmas (with crono): 174 

As mentioned in a comment, if no unit is specified until returns Period.

Snippet from the documentation:

A date-based amount of time in the ISO-8601 calendar system, such as ‘2 years, 3 months and 4 days’.
This class models a quantity or amount of time in terms of years, months, and days. See Duration for the time-based equivalent to this class.

The gotcha I just encountered with the first version of until is that it returns a Period object. That’ll return a number of years/months/days between the two dates, not the actual number of days. And getDays() on the Period only returns the days part (not taking into account the number of years or months), rather than the total number of days. The second version works exactly as desired to get a number of days between two dates.

DAYS.between

You can use DAYS.between from java.time.temporal.ChronoUnit

import java.time.temporal.ChronoUnit; . long totalDaysBetween(LocalDate dateBefore, LocalDate dateAfter) < return DAYS.between(dateBefore, dateAfter); 

If startDate and endDate are instance of java.util.Date

We can use the between( ) method from ChronoUnit enum:

public long between(Temporal temporal1Inclusive, Temporal temporal2Exclusive) < //.. >

ChronoUnit.DAYS count days which completed 24 hours.

import java.time.temporal.ChronoUnit; ChronoUnit.DAYS.between(startDate.toInstant(), endDate.toInstant()); //OR ChronoUnit.DAYS.between(Instant.ofEpochMilli(startDate.getTime()), Instant.ofEpochMilli(endDate.getTime())); 

Use the DAYS in enum java.time.temporal.ChronoUnit . Below is the Sample Code :

Читайте также:  Php session handler read

Output : *Number of days between the start date : 2015-03-01 and end date : 2016-03-03 is ==> 368. **Number of days between the start date : 2016-03-03 and end date : 2015-03-01 is ==> -368*

package com.bitiknow.date; import java.time.LocalDate; import java.time.temporal.ChronoUnit; /** * * @author pradeep * */ public class LocalDateTimeTry < public static void main(String[] args) < // Date in String format. String dateString = "2015-03-01"; // Converting date to Java8 Local date LocalDate startDate = LocalDate.parse(dateString); LocalDate endtDate = LocalDate.now(); // Range = End date - Start date Long range = ChronoUnit.DAYS.between(startDate, endtDate); System.out.println("Number of days between the start date : " + dateString + " and end date : " + endtDate + " is ==>" + range); range = ChronoUnit.DAYS.between(endtDate, startDate); System.out.println("Number of days between the start date : " + endtDate + " and end date : " + dateString + " is ==> " + range); > > 

Источник

Оцените статью