The class LocalDateTime is a combination of LocalDate and LocalTime without a time-zone, such as 2017-12-03T22:30. It could be used to store a date and time of a transaction in a payment system. As in the LocalTime class, time is represented to nanosecond precision.
An instance of LocalDateTime that represents this moment can be obtained as below:
LocalDateTime now = LocalDateTime.now(); // this momentThe class has static methods of and parse to create instances:
LocalDateTime dt1 = LocalDateTime.of(2017, 11, 25, 22, 30); // 25 November 2017, 22:30
LocalDateTime dt2 = LocalDateTime.parse("2017-11-25T22:30"); // 25 November 2017, 22:30It's possible to obtain an instance from a date and time:
LocalDate date = LocalDate.of(2017, 11, 25); // 2017-11-25
LocalTime time = LocalTime.of(21, 30); // 21:30
LocalDateTime dateTime = LocalDateTime.of(date, time); // 2017-11-25T21:30or using special instance methods of LocalDate and LocalTime:
LocalDate date = LocalDate.of(2017, 11, 25); // 2017-11-25
LocalTime time = LocalTime.of(21, 30); // 21:30
LocalDateTime dateTime1 = date.atTime(time); // 2017-11-25T21:30
LocalDateTime dateTime2 = time.atDate(date); // 2017-11-25T21:30The class LocalDateTime has methods for obtaining units of date and time:
LocalDateTime dateTime = LocalDateTime.of(2017, 11, 25, 22, 30); // 25 November 2017, 22:30
int month = dateTime.getMonthValue(); // 11
int day = dateTime.getDayOfMonth(); // 25
int hour = dateTime.getHour(); // 22
int minute = dateTime.getMinute(); // 30Also, the class has instance methods toLocalDate and toLocalTime to get the date and time parts of LocalDateTime.
The class has methods to add/subtract/alter years, months, days, hours, minutes, seconds as well as LocalDate and LocalTime.
LocalDateTime endOf2017 = LocalDateTime.of(2017, 12, 31, 23, 59, 59); // 2017-12-31T23:59:59
LocalDateTime beginningOf2018 = endOf2017.plusSeconds(1); // 2018-01-01T00:00
LocalDateTime beginningOf2020 = beginningOf2018.withYear(2020); // 2020-01-01T00:00So, LocalDateTime is another immutable class from the java.time package. It represents a combination of LocalDate and LocalTime.