Ngày và giờ Java
Ngày Java
Java không có lớp Date tích hợp nhưng chúng ta có thể nhập gói java.time
để làm việc với API ngày và giờ. Gói này bao gồm nhiều lớp ngày và giờ. Ví dụ:
Class | Description |
---|---|
LocalDate |
Represents a date (year, month, day (yyyy-MM-dd)) |
LocalTime |
Represents a time (hour, minute, second and nanoseconds (HH-mm-ss-ns)) |
LocalDateTime |
Represents both a date and a time (yyyy-MM-dd-HH-mm-ss-ns) |
DateTimeFormatter |
Formatter for displaying and parsing date-time objects |
Nếu bạn không biết gói là gì, hãy đọc Hướng dẫn về gói Java của chúng tôi.
Hiển thị ngày hiện tại
Để hiển thị ngày hiện tại, hãy nhập lớp java.time.LocalDate
và sử dụng phương thức now()
của nó:
Ví dụ
import java.time.LocalDate; // import the LocalDate class 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 } }
Đầu ra sẽ là:
Hiển thị thời gian hiện tại
Để hiển thị thời gian hiện tại (giờ, phút, giây và nano giây), hãy nhập lớp java.time.LocalTime
và sử dụng phương thức now()
của nó:
Ví dụ
import java.time.LocalTime; // import the LocalTime class public class Main { public static void main(String[] args) { LocalTime myObj = LocalTime.now(); System.out.println(myObj); } }
Đầu ra sẽ là:
Hiển thị ngày và giờ hiện tại
Để hiển thị ngày và giờ hiện tại, hãy nhập lớp java.time.LocalDateTime
và sử dụng phương thức now()
của nó:
Ví dụ
import java.time.LocalDateTime; // import the LocalDateTime class public class Main { public static void main(String[] args) { LocalDateTime myObj = LocalDateTime.now(); System.out.println(myObj); } }
Đầu ra sẽ là:
Định dạng ngày và giờ
Chữ "T" trong ví dụ trên được dùng để phân tách ngày và giờ. Bạn có thể sử dụng lớp DateTimeFormatter
với phương thức ofPattern()
trong cùng một gói để định dạng hoặc phân tích các đối tượng ngày giờ. Ví dụ sau sẽ xóa cả "T" và nano giây khỏi ngày giờ:
Ví dụ
import java.time.LocalDateTime; // Import the LocalDateTime class import java.time.format.DateTimeFormatter; // Import the DateTimeFormatter class public class Main { public static void main(String[] args) { LocalDateTime myDateObj = LocalDateTime.now(); System.out.println("Before formatting: " + myDateObj); DateTimeFormatter myFormatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss"); String formattedDate = myDateObj.format(myFormatObj); System.out.println("After formatting: " + formattedDate); } }
Đầu ra sẽ là:
Phương thức ofPattern()
chấp nhận tất cả các loại giá trị nếu bạn muốn hiển thị ngày và giờ ở định dạng khác. Ví dụ:
Value | Example | Tryit |
---|---|---|
yyyy-MM-dd | "1988-09-29" | Try it » |
dd/MM/yyyy | "29/09/1988" | Try it » |
dd-MMM-yyyy | "29-Sep-1988" | Try it » |
E, MMM dd yyyy | "Thu, Sep 29 1988" | Try it » |