I have a method that I take a startTime String and a endTime String convert to LocalDateTime and compare the hours difference between and generate the values in a ArrayList. For example if I have startTime: "2023-09-14T12:00:00", endTime: "2023-09-14T14:00:00", the method will find the value 2023-09-14T13:00:00 and it will add it in the ArrayList. The problem is that when the values are converted from String to LocalDateTime the seconds doesnt appear in the format like this : 2023-09-14T13:00 .
public static ArrayList<LocalDateTime> calculateHours(String startTime, tring endTime) {
// Parse the combined strings to LocalDateTime
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
LocalDateTime startDateTime = LocalDateTime.parse(startTime,formatter);
LocalDateTime endDateTime = LocalDateTime.parse(endTime,formatter);
// Calculate the difference in hours
long hoursDifference = java.time.Duration.between(startDateTime, endDateTime).toHours();
// Create an ArrayList to store LocalDateTime objects
ArrayList<LocalDateTime> hoursList = new ArrayList<>();
// Add each hour to the ArrayList with seconds included
for (long i = 0; i < hoursDifference; i++) {
LocalDateTime currentHour = startDateTime.plusHours(i);
hoursList.add(currentHour);
}
return hoursList;
}
The problem is that when the values are converted from String to LocalDateTime the seconds doesnt appear in the format like this : 2023-09-14T13:00 ."
That's talking about a conversion back to string, which would use LocalDateTime.toString()
by default - and that omits the seconds when the value is 0, as documented. In other words, you can see the same behavior with
LocalDateTime ldt = LocalDateTime.of(2023, 9, 14, 13, 0, 0);
System.out.println(ldt); // Prints 2023-09-14T13:00
In other words, nothing is going wrong - you're just misinterpreting however you're looking at the values in the list. If you need the values to be formatted in a specific way, you'll need to specify a DateTimeFormatter
(such as the one you've already created) and call ldt.format(formatter)
.