Java date diff in hours

KnpCode

In this post we’ll see how to calculate date and time difference in Java in terms of Years, months, days and hours, minutes, seconds.

To calculate difference between two dates in Java you can use SimpleDateFormat class though using that involves a lot of manual calculation and it doesn’t take time zones, day light saving into account.

To mitigate these shortcoming a new Date and Time API is added in Java 8 which provides classes to calculate date and time difference using inbuilt methods and also take into consideration time zones, day light saving and leap years while calculating difference.

Difference between two dates Using SimpleDateFormat

import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.TimeUnit; public class DifferenceDate < public static void main(String[] args) < try < dateDiff("15/08/2019 09:10:05", "04/09/2019 14:22:15", "dd/MM/yyyy HH:mm:ss"); >catch (ParseException e) < // TODO Auto-generated catch block e.printStackTrace(); >> private static void dateDiff(String date1, String date2, String pattern) throws ParseException < SimpleDateFormat sdf = new SimpleDateFormat(pattern); Date d1 = sdf.parse(date1); Date d2 = sdf.parse(date2); long diffInMillis = d2.getTime() - d1.getTime(); long daysDiff = TimeUnit.DAYS.convert(diffInMillis, TimeUnit.MILLISECONDS); long hoursDiff = TimeUnit.HOURS.convert(diffInMillis - (daysDiff * 24 * 60 * 60 * 1000), TimeUnit.MILLISECONDS); long minutesDiff = TimeUnit.MINUTES.convert(diffInMillis - (daysDiff * 24 * 60 * 60 * 1000) - (hoursDiff * 60 * 60 * 1000), TimeUnit.MILLISECONDS); long secondsDiff = TimeUnit.SECONDS.convert(diffInMillis - (daysDiff * 24 * 60 * 60 * 1000) - (hoursDiff * 60 * 60 * 1000) - (minutesDiff * 60 * 1000), TimeUnit.MILLISECONDS); System.out.println(daysDiff + " day(s) " + hoursDiff + " Hour(s) " + minutesDiff + " Minute(s) " + secondsDiff + " Second(s)"); >>
20 day(s) 5 Hour(s) 12 Minute(s) 10 Second(s)

As you can see using SimpleDateFormat requires lot of manual effort where you need to convert as per the required time unit.

Difference between two dates using Java 8 classes

In the new date and time API in Java 8 there are following classes that can be used for date difference calculation.

  • java.time.Period— A date-based amount of time, supported units of a period are YEARS, MONTHS and DAYS.
  • java.time.Duration— A time-based amount of time. This class models a quantity or amount of time in terms of seconds and nanoseconds. It can be accessed using other duration-based units, such as minutes and hours.
  • java.time.temporal.TemporalUnit— TemporalUnit is an interface that represents a unit of date-time, such as Days or Hours.
  • java.time.temporal.ChronoUnit— It is an Enum that implements TemporalUnit interface.

Difference between two dates in terms of years, months, days

Difference between two dates in date-based amount of time can be calculated using Period class.

import java.time.LocalDate; import java.time.Period; public class DifferenceDate < public static void main(String[] args) < LocalDate date1 = LocalDate.of(2018, 8, 15); LocalDate date2 = LocalDate.of(2019, 9, 4); dateDiff(date1, date2); >private static void dateDiff(LocalDate date1, LocalDate date2) < Period p = Period.between(date1, date2); System.out.printf("%d Year(s) %d Month(s) %d Day(s)", p.getYears(), p.getMonths(), p.getDays()); >>

Difference between two dates in terms of days, hours, minutes, seconds

Difference between two dates in a time-based amount of time can be calculated using Duration class.

public class DifferenceDate < public static void main(String[] args) < LocalDateTime date1 = LocalDateTime.of(2019, 9, 3, 9, 10, 5); LocalDateTime date2 = LocalDateTime.of(2019, 9, 4, 14, 22, 15); dateDiff(date1, date2); >private static void dateDiff(LocalDateTime date1, LocalDateTime date2) < Duration d = Duration.between(date1, date2); System.out.printf("%d Day(s) %d Hour(s) %d Minute(s) %d Second(s)", d.toDays(), d.toHoursPart(), d.toMinutesPart(), d.toSecondsPart()); >>
1 Day(s) 5 Hour(s) 12 Minute(s) 10 Second(s)

Using both Period and Duration classes to calculate date difference

import java.time.Duration; import java.time.LocalDateTime; import java.time.Period; public class DifferenceDate < public static void main(String[] args) < LocalDateTime date1 = LocalDateTime.of(2018, 7, 2, 12, 18, 13); LocalDateTime date2 = LocalDateTime.of(2019, 9, 4, 14, 22, 15); dateDiff(date1, date2); >private static void dateDiff(LocalDateTime date1, LocalDateTime date2) < Period p = Period.between(date1.toLocalDate(), date2.toLocalDate()); Duration d = Duration.between(date1, date2); System.out.printf("%d Year(s) %d Month(s) %d Day(s) %d Hour(s) %d Minute(s) %d Second(s)", p.getYears(), p.getMonths(), p.getDays(), d.toHoursPart(), d.toMinutesPart(), d.toSecondsPart()); >>
1 Year(s) 2 Month(s) 2 Day(s) 2 Hour(s) 4 Minute(s) 2 Second(s)

Using ChronoUnit to find difference

If you want the total difference in terms of units then ChronoUnit can also be used.

public class DifferenceDate < public static void main(String[] args) < LocalDateTime date1 = LocalDateTime.of(2019, 9, 3, 9, 10, 5); LocalDateTime date2 = LocalDateTime.of(2019, 9, 4, 14, 22, 15); dateDiff(date1, date2); >private static void dateDiff(LocalDateTime date1, LocalDateTime date2) < long daysDiff = ChronoUnit.DAYS.between(date1, date2); long hoursDiff = ChronoUnit.HOURS.between(date1, date2); long minutesDiff = ChronoUnit.MINUTES.between(date1, date2); long secondsDiff = ChronoUnit.SECONDS.between(date1, date2); long millisDiff = ChronoUnit.MILLIS.between(date1, date2); long nanoDiff = ChronoUnit.NANOS.between(date1, date2); System.out.println("Days- "+ daysDiff); System.out.println("Hours- "+ hoursDiff); System.out.println("Minutes- "+ minutesDiff); System.out.println("Seconds- "+ secondsDiff); System.out.println("Millis- "+ millisDiff); System.out.println("Nano Seconds- "+ nanoDiff); >>
Days- 1 Hours- 29 Minutes- 1752 Seconds- 105130 Millis- 105130000 Nano Seconds- 105130000000000

That’s all for the topic Java Date Difference Program. If something is missing or you have something to share about the topic please write a comment.

Источник

Читайте также:  Php обмен значениями переменных

Difference Between Two Dates in Java

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Читайте также:  Java разбиение строки регулярным выражением

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Overview

In this quick tutorial, we’ll explore multiple possibilities of calculating the difference between two dates in Java.

Further reading:

Increment Date in Java

Check If a String Is a Valid Date in Java

2. Core Java

2.1. Using java.util.Date to Find the Difference in Days

Let’s start by using the core Java APIs to do the calculation and determine the number of days between the two dates:

@Test public void givenTwoDatesBeforeJava8_whenDifferentiating_thenWeGetSix() throws ParseException < SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH); Date firstDate = sdf.parse("06/24/2017"); Date secondDate = sdf.parse("06/30/2017"); long diffInMillies = Math.abs(secondDate.getTime() - firstDate.getTime()); long diff = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS); assertEquals(6, diff); >

2.2. Using java.time.temporal.ChronoUnit to Find the Difference

The Time API in Java 8 represents a unit of date-time, e.g. seconds or days, using TemporalUnit interface.

Each unit provides an implementation for a method named between to calculate the amount of time between two temporal objects in terms of that specific unit.

For example, in order to calculate the seconds between two LocalDateTimes:

@Test public void givenTwoDateTimesInJava8_whenDifferentiatingInSeconds_thenWeGetTen()

ChronoUnit provides a set of concrete time units by implementing the TemporalUnit interface. It’s highly recommended to static import the ChronoUnit enum values to achieve better readability:

import static java.time.temporal.ChronoUnit.SECONDS; // omitted long diff = SECONDS.between(now, tenSecondsLater);

Also, we can pass any two compatible temporal objects to the between method, even the ZonedDateTime.

What’s great about ZonedDateTime is that the calculation will work even if they are set to different time zones:

@Test public void givenTwoZonedDateTimesInJava8_whenDifferentiating_thenWeGetSix() < LocalDateTime ldt = LocalDateTime.now(); ZonedDateTime now = ldt.atZone(ZoneId.of("America/Montreal")); ZonedDateTime sixMinutesBehind = now .withZoneSameInstant(ZoneId.of("Asia/Singapore")) .minusMinutes(6); long diff = ChronoUnit.MINUTES.between(sixMinutesBehind, now); assertEquals(6, diff); >

2.3. Using Temporal#until()

Any Temporal object, such as LocalDate or ZonedDateTime,provides an until method to calculate the amount of time until another Temporal in terms of the specified unit:

@Test public void givenTwoDateTimesInJava8_whenDifferentiatingInSecondsUsingUntil_thenWeGetTen()

The Temporal#until and TemporalUnit#between are two different APIs for the same functionality.

Читайте также:  Python preventing sql injection

2.4. Using java.time.Duration and java.time.Period

In Java 8, the Time API introduced two new classes: Duration and Period.

If we want to calculate the difference between two date-times in a time-based (hour, minutes, or seconds) amount of time, we can use the Duration class:

@Test public void givenTwoDateTimesInJava8_whenDifferentiating_thenWeGetSix()

However, we should be wary of a pitfall if we try using the Period class to represent the difference between two dates.

An example will explain this pitfall quickly.

Let’s calculate how many days between two dates using the Period class:

@Test public void givenTwoDatesInJava8_whenUsingPeriodGetDays_thenWorks()

If we run the test above, it’ll pass. We may think the Period class is convenient to solve our problem. So far, so good.

If this way works with a difference of six days, we don’t doubt that it’ll work for 60 days as well.

So let’s change the 6 in the test above to 60 and see what happens:

@Test public void givenTwoDatesInJava8_whenUsingPeriodGetDays_thenDoesNotWork()

Now if we run the test again, we’ll see:

java.lang.AssertionError: Expected :60 Actual :29

Oops! Why did the Period class report the difference as 29 days?

This is because the Period class represents a date-based amount of time in the format of “x years, y months and z days”. When we call its getDays() method, it returns only the “z days” part.

Therefore, the period object in the test above holds the value “0 years, 1 month and 29 days”:

@Test public void givenTwoDatesInJava8_whenUsingPeriod_thenWeGet0Year1Month29Days() < LocalDate aDate = LocalDate.of(2020, 9, 11); LocalDate sixtyDaysBehind = aDate.minusDays(60); Period period = Period.between(aDate, sixtyDaysBehind); int years = Math.abs(period.getYears()); int months = Math.abs(period.getMonths()); int days = Math.abs(period.getDays()); assertArrayEquals(new int[] < 0, 1, 29 >, new int[] < years, months, days >); >

If we want to calculate the difference in days using Java 8’s Time API, the ChronoUnit.DAYS.between() method is the most straightforward way.

3. External Libraries

3.1. JodaTime

We can also do a relatively straightforward implementation with JodaTime:

You can get the latest version of Joda-time from Maven Central.

@Test public void givenTwoDatesInJodaTime_whenDifferentiating_thenWeGetSix()

Similarly, with LocalDateTime:

@Test public void givenTwoDateTimesInJodaTime_whenDifferentiating_thenWeGetSix()

3.2. Date4J

Date4j also provides a straightforward and simple implementation — noting that, in this case, we need to explicitly provide a TimeZone.

Let’s start with the Maven dependency:

 com.darwinsys hirondelle-date4j 1.5.1 

Here’s a quick test working with the standard DateTime:

@Test public void givenTwoDatesInDate4j_whenDifferentiating_thenWeGetSix()

4. Conclusion

In this article, we illustrated a few ways of calculating the difference between dates (with and without time), both in plain Java as well as using external libraries.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

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