40 lines
1.8 KiB
Plaintext
40 lines
1.8 KiB
Plaintext
hopw to get the minute difference between two localdatetime variables in java of the pattern dd.mm.yyyy hh:mm
|
||
ChatGPT:
|
||
ChatGPT
|
||
To calculate the minute difference between two LocalDateTime variables in Java with a pattern dd.MM.yyyy HH:mm, you can follow these steps:
|
||
|
||
Parse the date-time strings into LocalDateTime objects using DateTimeFormatter.
|
||
Use Duration.between() to get the difference between the two LocalDateTime objects.
|
||
Retrieve the difference in minutes from the Duration.
|
||
Here’s an example of how to implement this:
|
||
|
||
java
|
||
Code kopieren
|
||
import java.time.Duration;
|
||
import java.time.LocalDateTime;
|
||
import java.time.format.DateTimeFormatter;
|
||
|
||
public class MinuteDifferenceExample {
|
||
public static void main(String[] args) {
|
||
// Define the date format
|
||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm");
|
||
|
||
// Parse the two LocalDateTime objects
|
||
LocalDateTime dateTime1 = LocalDateTime.parse("06.10.2024 14:30", formatter);
|
||
LocalDateTime dateTime2 = LocalDateTime.parse("06.10.2024 16:45", formatter);
|
||
|
||
// Calculate the duration between the two
|
||
Duration duration = Duration.between(dateTime1, dateTime2);
|
||
|
||
// Get the difference in minutes
|
||
long minutesDifference = duration.toMinutes();
|
||
|
||
System.out.println("Minute difference: " + minutesDifference);
|
||
}
|
||
}
|
||
Explanation:
|
||
DateTimeFormatter: This formats the LocalDateTime according to the provided pattern (dd.MM.yyyy HH:mm).
|
||
LocalDateTime.parse(): Converts the date-time strings to LocalDateTime objects using the specified formatter.
|
||
Duration.between(): Computes the duration between the two LocalDateTime instances.
|
||
duration.toMinutes(): Extracts the total minutes of difference.
|
||
This will print the minute difference between the two date-time values. |