LocalDateTime trong java

LocalDateTime là sự kết hợp giữa LocalDateLocalTime. LocalDateTime biểu diễn thời gian chính xác đến từng phút giây được áp dụng cho các trường hợp cần ghi dấu lịch sử etc.

Note: LocalDateTime là Immutable

Khởi tạo LocalDateTime

Để khởi tạo LocalDateTime object chúng ta có nhiều cách, hai trong số các cách thường được sử dụng là LocalDateTime.now()LocalDateTime.of().

LocalDateTime localDateTime = LocalDateTime.now();

LocalDateTime localDateTime2 =
    LocalDateTime.of(2020, 11, 26, 13, 55, 36, 123);

Truy xuất giá trị LocalDateTime

LocalDateTime object có rất nhiều giá trị chúng ta có thể lấy từ ngày, tháng, năm đến giờ, phút giây etc. Chúng ta sẽ cùng nhau điểm qua các method giúp chúng ta lấy các giá trị tương ứng.

  • getYear()
  • getMonth()
  • getDayOfMonth()
  • getDayOfWeek()
  • getDayOfYear()
  • getHour()
  • getMinute()
  • getSecond()
  • getNano()
import java.time.LocalDateTime;

class LocalDateExample {
    public static void main(String[] args) {
        LocalDateTime localDateTime =  LocalDateTime.of(2020, 11, 26, 13, 55, 36, 123);

        System.out.println("Year: " + localDateTime.getYear());

        System.out.println("Month: " + localDateTime.getMonth());

        System.out.println("Day of Month: " + localDateTime.getDayOfMonth());

        System.out.println("Day of Week: " + localDateTime.getDayOfWeek());

        System.out.println("Day of Year: " + localDateTime.getDayOfYear());

        System.out.println("Hour: " + localDateTime.getHour());

        System.out.println("Minute: " + localDateTime.getMinute());

        System.out.println("Second: " + localDateTime.getSecond());

        System.out.println("Nano: " + localDateTime.getNano());

    }
}

Output:

Year: 2020
Month: NOVEMBER
Day of Month: 26
Day of Week: THURSDAY
Day of Year: 331
Hour: 13
Minute: 55
Second: 36
Nano: 123

plus và minus trong LocalDateTime

Để cộng trừ các giá trị của LocalDateTime object chúng ta có thể sử dụng các method:

  • plusYears()
  • plusMonths()
  • plusDays()
  • plusHours()
  • plusMinutes()
  • plusSeconds()
  • plusNanos()
  • minusYears()
  • minusMonths()
  • minusDays()
  • minusHours()
  • minusMinutes()
  • minusSeconds()
  • minusNanos()
LocalDateTime localDateTime  = LocalDateTime.now();

LocalDateTime localDateTime1 = localDateTime.plusYears(3);
LocalDateTime localDateTime2 = localDateTime.minusYears(3);
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x