java calculate delta time

java calculate delta time

To calculate the difference between two dates or times in Java, you can use the 'Duration' class of the 'java.time' library. The 'Duration' class represents a period of time in units of seconds and nanoseconds and can be used to calculate the difference between two instances of 'Temporal' (such as 'LocalDateTime' or 'Instant').

Here is an example of how to calculate the difference between two dates using the 'Duration' class:

re‮ref‬ to:lautturi.com
import java.time.Duration;
import java.time.LocalDate;

public class Main {
  public static void main(String[] args) {
    // Sets two dates
    LocalDate data1 = LocalDate.of(2020, 1, 1);
    LocalDate data2 = LocalDate.of(2021, 1, 1);

    // Calculates the difference between the two dates
    Duration delta = Duration.between(data1, data2);

    // Prints the difference in days
    System.out.println(delta.toDays());  // Prints: 365
  }
}

This code creates two instances of the 'LocalDate' class representing the dates January 1, 2020 and January 1, 2021, respectively. It then uses the static 'between' method of the 'Duration' class to calculate the difference between the two dates and stores the result in a 'delta' variable. Finally, it prints the difference in days using the 'toDays' method.

You can also calculate the difference between two hours using the 'Duration' class by simply replacing the 'LocalDate' instances with instances of 'LocalTime' or 'LocalDateTime'. For instance:

import java.time.Duration;
import java.time.LocalTime;

public class Main {
  public static void main(String[] args) {
    // Sets two hours
    LocalTime hora1 = LocalTime.of(12, 0);
    LocalTime hora2 = LocalTime.of(14, 0);

    // Calculates the difference between the two hours
    Duration delta = Duration.between(hora1, hora2);

    // Prints the difference in minutes
    System.out.println(delta.toMinutes());   
 }
}
Created Time:2017-11-03 00:14:47  Author:lautturi