Получить следующий конкретный LocalDateTime в текущую дату ИЛИ возврат следующего конкретного LocalDateTime
Я хочу создать экземпляр LocalDateTime в дату / время следующего (например) 5:00 AM
.
ТРЕБОВАНИЕ:
- Текущее LocalDateTime>
2020-08-14T10:57:45.592035
, НЕОБХОДИМО вернуться2020-08-15T05:00:00.000000
- Текущее LocalDateTime>
2020-08-14T02:57:45.592035
, НЕОБХОДИМО вернуть2020-08-14T05:00:00.000000
Есть ли какой-либо метод в Java Time API, или я должен делать расчеты вручную, например, по умолчанию 5:00 AM в текущей дате и Сравнить, чтобы вернуть (установить) дату С текущей датой, если меньше, чем Добавить плюс дней (1) и 5:00 AM ELSE вернуть дату SET?
Обратитесь: dateTime.with(TemporalAdjusters.next(DayOfWeek.MONDAY))
// Но он возвращается в следующий понедельник с сегодняшнего дня (текущая дата).
Есть ручное решение>
LocalDateTime currentDateTimeInLosAngeles = LocalDateTime.now(ZoneId.of(timeZone));
LocalDateTime nextTimeAt530 = null;
System.out.println(currentDateTimeInLosAngeles);
if (currentDateTimeInLosAngeles.toLocalTime().isAfter(LocalTime.of(5, 30, 0, 0))) {
System.out.println("Next Day at 5:30");
nextTimeAt530 = LocalDateTime.of(LocalDate.now(ZoneId.of(timeZone)), LocalTime.of(5, 30, 0, 0))
.plusDays(1);
System.out.println(nextTimeAt530);
} else {
System.out.println("Current Day at 5:30");
nextTimeAt530 = LocalDateTime.of(LocalDate.now(ZoneId.of(timeZone)), LocalTime.of(5, 30, 0));
System.out.println(nextTimeAt530);
}
System.out.println("\n -- FOR MAIN DIFFERENCE");
System.out.println(currentDateTimeInLosAngeles);
System.out.println(nextTimeAt530);
1 ответ
Сделать это можно следующим образом:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// Given date-time string
String strDateTime = "2020-08-14T10:57:45.592035";
// Get LocalDateTime by parsing the date-time string
LocalDateTime ldt = LocalDateTime.parse(strDateTime);
// Get a new LocalDateTime instance with the time as 5:00:00:00.0
// in the parsed LocalDateTime
ldt = ldt.withHour(5)
.withMinute(0)
.withSecond(0)
.withNano(0);
System.out.println(ldt);
// Define the format to get the date-time string representation of LocalDateTime
// in the desired pattern
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS");
// Get string representation of LocalDateTime in the desired pattern
String formattedDateTimeStr = formatter.format(ldt);
System.out.println(formattedDateTimeStr);
// Add one day
ldt = ldt.plusDays(1);
System.out.println(ldt);
// Get string representation of LocalDateTime in the desired pattern
formattedDateTimeStr = formatter.format(ldt);
System.out.println(formattedDateTimeStr);
}
}
Выход:
2020-08-14T05:00
2020-08-14T05:00:00.000000
2020-08-15T05:00
2020-08-15T05:00:00.000000
LocalDateTime#isBefore
& LocalDateTime#isAfter
Используйте эти методы, чтобы проверить, находится ли дата до / после другого.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// Given date-time string
String strDateTime = "2020-08-14T02:57:45.592035";
// Get LocalDateTime by parsing the date-time string
LocalDateTime ldtGiven = LocalDateTime.parse(strDateTime);
System.out.println(ldtGiven);
// Get a new LocalDateTime instance with the time as 5:00:00:00.0
// in the parsed LocalDateTime
LocalDateTime ldtGivenWith5AM = ldtGiven.withHour(5)
.withMinute(0)
.withSecond(0)
.withNano(0);
// Check if the time is before 5:00
LocalDateTime ldtNew = null;
if (ldtGiven.isBefore(ldtGivenWith5AM)) {
ldtNew = ldtGivenWith5AM.plusDays(1);
}
System.out.println(ldtNew);
// Define the format to get the date-time string representation of LocalDateTime
// in the desired pattern
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS");
// Get string representation of LocalDateTime in the desired pattern
String formattedDateTimeStr = formatter.format(ldtNew);
System.out.println(formattedDateTimeStr);
}
}
Выход:
2020-08-14T02:57:45.592035
2020-08-15T05:00
2020-08-15T05:00:00.000000