Time

Duy Văn | 11/03/2025


Java không có class built-in nào để xử lý vấn đề thời gian, nhưng java.time package xử lý được, nó có 4 class chính:

  • LocalDate - Để xử lý ngày dạng yyyy-MM-dd
  • LocalTime - Để xử lý thời gian dạng HH-mm-ss
  • LocalDateTime - Để xử lý cả ngày và thời gian dạng yyyy-MM-dd-HH-mm-ss
  • DateTimeFormatter - Để định dạng ngày và thời gian

Ví dụ để hiển thị ngày hôm nay


import java.time.LocalDate;

public class Main {
  public static void main(String[] args) {
    LocalDate myObj = LocalDate.now(); // Create a date object
    System.out.println(myObj); // Display the current date
  }
}

Hay có thể thay đổi thành lấy thời gian với class LocalTime hay thậm chí chi tiết hơn với LocalDateTime

Formatting Date and Time

Một điểm quan trọng nữa là với DateTimeFormatter khi chúng ta muốn lấy ra thời gian theo format cụ thể, chúng ta sẽ sử dụng ofPattern() method


import java.time.LocalDateTime;
import java.time.format.DateTimeFormater;

public class Main{
  public static void main(String[] args){
    LocalDateTime dateObj = LocalDateTime.now();
    System.out.println("Before formatting: " + dateObj);
    DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
    String formattedDate = dateObj.format(myFormatObj);
    System.out.println("After formatting: " + formattedDate);
  }
}

Cụ thể để sử dụng ofPattern thì chỉ cần nhớ những cú pháp sau:

  • yyyy - Năm
  • MM - Tháng
  • dd - Ngày
  • HH - Giờ
  • mm - Phút
  • ss - Giây
  • E - Ngày trong tuần