Localdatetime java разница во времени

How can I calculate a time difference in Java?

I want to subtract two time periods say 16:00:00 from 19:00:00. Is there any Java function for this? The results can be in milliseconds, seconds, or minutes.

19 Answers 19

Java 8 has a cleaner solution — Instant and Duration

import java.time.Duration; import java.time.Instant; . Instant start = Instant.now(); //your code Instant end = Instant.now(); Duration timeElapsed = Duration.between(start, end); System.out.println("Time taken: "+ timeElapsed.toMillis() +" milliseconds"); 

So this boils down to two imports and System.out.println(«Duration: » + String.valueOf(Duration.between(outerstart, Instant.now()).toMillis())); to log the duration. I wouldn’t call that a nice and clean solution in Java8 if other languages can do it with code like print(«Duration: » + str(time.time()-start)) .

@Luc cleanliness isn’t the same as brevity. It’s much clearer exactly what is happening in the Java 8 version, and it’s also much easier to tweak if, for example, you want to report the duration between two instants in a unit other than milliseconds, or as multiple units (e.g. 1h 15m 3.022s instead of 4503022 milliseconds ).

String time1 = "16:00:00"; String time2 = "19:00:00"; SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss"); Date date1 = format.parse(time1); Date date2 = format.parse(time2); long difference = date2.getTime() - date1.getTime(); 

Difference is in milliseconds.

Inverting the variables won’t do much good.. In this example, sure, you could invert them and take the absolute value or something. But what happens if you have midnight (00:00)?

what about the difference between 08:00:00 today and yesterday’s 10:00:00. I don’t think what you suggested is a breakable logic.

I want to get the minutes between 2 Dates (time) and them don’t have the midnight bcz my range times from 05h00m to 22h00m, so your answer helped me. Thanks bro!

Читайте также:  Css sticky table headers

To get pretty timing differences, then

// d1, d2 are dates long diff = d2.getTime() - d1.getTime(); long diffSeconds = diff / 1000 % 60; long diffMinutes = diff / (60 * 1000) % 60; long diffHours = diff / (60 * 60 * 1000) % 24; long diffDays = diff / (24 * 60 * 60 * 1000); System.out.print(diffDays + " days, "); System.out.print(diffHours + " hours, "); System.out.print(diffMinutes + " minutes, "); System.out.print(diffSeconds + " seconds."); 
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime dateTime1= LocalDateTime.parse("2014-11-25 19:00:00", formatter); LocalDateTime dateTime2= LocalDateTime.parse("2014-11-25 16:00:00", formatter); long diffInMilli = java.time.Duration.between(dateTime1, dateTime2).toMillis(); long diffInSeconds = java.time.Duration.between(dateTime1, dateTime2).getSeconds(); long diffInMinutes = java.time.Duration.between(dateTime1, dateTime2).toMinutes(); 

Just like any other language; convert your time periods to a unix timestamp (ie, seconds since the Unix epoch) and then simply subtract. Then, the resulting seconds should be used as a new unix timestamp and read formatted in whatever format you want.

Ah, give the above poster (genesiss) his due credit, code’s always handy 😉 Though, you now have an explanation as well 🙂

import java.util.Date; . Date d1 = new Date(); . . Date d2 = new Date(); System.out.println(d2.getTime()-d1.getTime()); //gives the time difference in milliseconds. System.out.println((d2.getTime()-d1.getTime())/1000); //gives the time difference in seconds. 

and, to show in a nicer format, you can use:

 DecimalFormat myDecimalFormatter = new DecimalFormat("###,###.###"); System.out.println(myDecimalFormatter.format(((double)d2.getTime()-d1.getTime())/1000)); 

This duplicates another answer and adds no new content. Please don’t post an answer unless you actually have something new to contribute.

@DavidPostill, thank you for your heads up. But the solution I needed myself and didn’t find in the GENESIS’s post was the time difference between the execution of two lines of code (like the starting point and ending point of program or before and after running a method, not some static times). I thought this may help.

Besides the most common approach with Period and Duration objects you can widen your knowledge with another way for dealing with time in Java.

Advanced Java 8 libraries. ChronoUnit for Differences.

ChronoUnit is a great way to determine how far apart two Temporal values are. Temporal includes LocalDate, LocalTime and so on.

LocalTime one = LocalTime.of(5,15); LocalTime two = LocalTime.of(6,30); LocalDate date = LocalDate.of(2019, 1, 29); System.out.println(ChronoUnit.HOURS.between(one, two)); //1 System.out.println(ChronoUnit.MINUTES.between(one, two)); //75 System.out.println(ChronoUnit.MINUTES.between(one, date)); //DateTimeException 

First example shows that between truncates rather than rounds.

Читайте также:  Php как получить поддомен

The second shows how easy it is to count different units.

And the last example reminds us that we should not mess up with dates and times in Java 🙂

Источник

Java 8 – Разница между двумя локальными датами или локальным временем

В Java 8 мы можем использовать Период , Длительность или Хронометр для вычисления разницы между двумя Локальными датами или локальным временем .

  1. Период для расчета разницы между двумя Локальными датами .
  2. Продолжительность для вычисления разницы между двумя Локальное время .
  3. Хроноунит для всего.

1. Период

package com.mkyong.java8; import java.time.LocalDate; import java.time.Period; public class JavaLocalDate < public static void main(String[] args) < LocalDate from = LocalDate.of(2020, 5, 4); LocalDate to = LocalDate.of(2020, 10, 10); Period period = Period.between(from, to); System.out.print(period.getYears() + " years,"); System.out.print(period.getMonths() + " months,"); System.out.print(period.getDays() + " days"); >>

2. Продолжительность

package com.mkyong.java8; import java.time.Duration; import java.time.LocalDateTime; public class JavaLocalDateTime < public static void main(String[] args) < LocalDateTime from = LocalDateTime.of(2020, 10, 4, 10, 20, 55); LocalDateTime to = LocalDateTime.of(2020, 10, 10, 10, 21, 1); Duration duration = Duration.between(from, to); // days between from and to System.out.println(duration.toDays() + " days"); // hours between from and to System.out.println(duration.toHours() + " hours"); // minutes between from and to System.out.println(duration.toMinutes() + " minutes"); // seconds between from and to System.out.println(duration.toSeconds() + " seconds"); System.out.println(duration.getSeconds() + " seconds"); >>
6 days 144 hours 8640 minutes 518406 seconds 518406 seconds

3. Хроноблок

package com.mkyong.java8; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; public class JavaChronoUnit < public static void main(String[] args) < LocalDateTime from = LocalDateTime.of(2020, 10, 4, 10, 20, 55); LocalDateTime to = LocalDateTime.of(2020, 11, 10, 10, 21, 1); long years = ChronoUnit.YEARS.between(from, to); long months = ChronoUnit.MONTHS.between(from, to); long weeks = ChronoUnit.WEEKS.between(from, to); long days = ChronoUnit.DAYS.between(from, to); long hours = ChronoUnit.HOURS.between(from, to); long minutes = ChronoUnit.MINUTES.between(from, to); long seconds = ChronoUnit.SECONDS.between(from, to); long milliseconds = ChronoUnit.MILLIS.between(from, to); long nano = ChronoUnit.NANOS.between(from, to); System.out.println(years + " years"); System.out.println(months + " months"); System.out.println(weeks + " weeks"); System.out.println(days + " days"); System.out.println(hours + " hours"); System.out.println(minutes + " minutes"); System.out.println(seconds + " seconds"); System.out.println(milliseconds + " milliseconds"); System.out.println(nano + " nano"); >>
0 years 1 months 5 weeks 37 days 888 hours 53280 minutes 3196806 seconds 3196806000 milliseconds 3196806000000000 nano

Рекомендации

Источник

Читайте также:  Java lang throwable methods

Расчёт разницы между двумя датами в Java

Одной из распространённых задач в программировании является расчёт разницы между двумя датами. Примером может быть необходимость определить количество лет, месяцев, дней, часов, минут и секунд между двумя точками во времени, представленными в виде объектов LocalDateTime .

Существует несколько способов решения этой задачи в Java, но одним из наиболее эффективных и надёжных является использование классов Period и Duration из пакета java.time , который был добавлен в Java 8.

import java.time.Duration; import java.time.LocalDateTime; import java.time.Period; public class Main < public static void main(String[] args) < LocalDateTime toDateTime = LocalDateTime.of(2014, 9, 9, 19, 46, 45); LocalDateTime fromDateTime = LocalDateTime.of(1984, 12, 16, 7, 45, 55); Period period = Period.between(fromDateTime.toLocalDate(), toDateTime.toLocalDate()); Duration duration = Duration.between(fromDateTime.toLocalTime(), toDateTime.toLocalTime()); System.out.println(period.getYears() + " years " + period.getMonths() + " months " + period.getDays() + " days " + duration.toHoursPart() + " hours " + duration.toMinutesPart() + " minutes " + duration.toSecondsPart() + " seconds."); >>

В этом примере используются два класса: Period и Duration . Класс Period используется для расчёта разницы между двумя датами, а класс Duration — для расчёта разницы между двумя временами.

Метод Period.between() принимает два объекта LocalDate и возвращает объект Period , который представляет период времени в годах, месяцах и днях между двумя датами.

Метод Duration.between() принимает два объекта LocalTime и возвращает объект Duration , который представляет продолжительность времени в часах, минутах и секундах между двумя временами.

Важно отметить, что методы toHoursPart() , toMinutesPart() и toSecondsPart() класса Duration доступны начиная с Java 9. Они возвращают часть продолжительности в соответствующих единицах времени, игнорируя большие единицы времени. Например, toHoursPart() вернёт количество часов без учёта дней, а toMinutesPart() — количество минут без учёта часов.

Источник

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