Bỏ qua để đến nội dung

Xử lý thời gian (LocalDate, LocalDateTime)

import java.time.LocalDate;
LocalDate today = LocalDate.now(); // ngày hiện tại
LocalDate birthday = LocalDate.of(2000, 5, 20); // năm, tháng, ngày cụ thể
System.out.println(today); // 2026-09-17 (định dạng ISO: yyyy-MM-dd)
System.out.println(birthday); // 2000-05-20
import java.time.LocalTime;
import java.time.LocalDateTime;
LocalTime now = LocalTime.now(); // chỉ giờ, ví dụ 14:30:15
LocalDateTime meeting = LocalDateTime.of(2026, 9, 20, 14, 30); // ngày + giờ cụ thể
System.out.println(now);
System.out.println(meeting); // 2026-09-20T14:30
LocalDate date = LocalDate.of(2026, 9, 17);
LocalDate nextWeek = date.plusWeeks(1); // cộng thêm 1 tuần
LocalDate lastMonth = date.minusMonths(1); // trừ đi 1 tháng
int year = date.getYear();
int dayOfMonth = date.getDayOfMonth();
var dayOfWeek = date.getDayOfWeek(); // ví dụ THURSDAY
System.out.println(date.isBefore(nextWeek)); // true
System.out.println(date.isAfter(lastMonth)); // true

⚠️ Giống String, các lớp trong java.time bất biến (immutable) - plusWeeks(), minusMonths() trả về một đối tượng mới, không sửa đối tượng gốc:

LocalDate date = LocalDate.now();
date.plusDays(5); // KHÔNG có tác dụng gì! Kết quả bị bỏ đi, date không đổi
LocalDate correct = date.plusDays(5); // ĐÚNG - gán lại vào biến mới

4. Định dạng ngày giờ với DateTimeFormatter

Phần tiêu đề “4. Định dạng ngày giờ với DateTimeFormatter”
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
LocalDate date = LocalDate.of(2026, 9, 17);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String formatted = date.format(formatter);
System.out.println(formatted); // 17/09/2026

5. Tính khoảng cách giữa hai mốc thời gian

Phần tiêu đề “5. Tính khoảng cách giữa hai mốc thời gian”
import java.time.LocalDate;
import java.time.Period;
LocalDate start = LocalDate.of(2026, 1, 1);
LocalDate end = LocalDate.of(2026, 9, 17);
Period period = Period.between(start, end);
System.out.println(period.getMonths() + " tháng, " + period.getDays() + " ngày");

6. Lưu ý: java.time thay thế Date/Calendar

Phần tiêu đề “6. Lưu ý: java.time thay thế Date/Calendar cũ”

Từ Java 8, java.time (LocalDate, LocalDateTime, LocalTime, Duration, Period,…) là cách được khuyến nghị để xử lý ngày giờ - thay thế cho java.util.Datejava.util.Calendar cũ vốn có API khó dùng và dễ gây lỗi (mutable, tháng đánh số từ 0,…).

  • LocalDate (chỉ ngày), LocalTime (chỉ giờ), LocalDateTime (cả hai) là các lớp cốt lõi của java.time
  • Các lớp này bất biến - luôn gán lại kết quả của plusX()/minusX() vào biến mới
  • DateTimeFormatter để định dạng ngày giờ theo mẫu tùy chỉnh
  • Ưu tiên java.time (Java 8+) thay vì Date/Calendar