Java Tut 34 : Thời gian ( ngày giờ) trong Java 0 (0)
Java không có lớp Ngày tích hợp sẵn, nhưng chúng ta có thể nhập java.time gói để 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, hãy nhập java.time.LocalDatelớp và sử dụng now()phương thức của nó :
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à:2021-11-07Hãy tự mình thử »
Để hiển thị thời gian hiện tại (giờ, phút, giây và nano giây), hãy nhập java.time.LocalTimelớp và sử dụng now()phương thức của nó :
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à:09:05:48.839290Hãy tự mình thử »
Để hiển thị ngày và giờ hiện tại, hãy nhập java.time.LocalDateTimelớp và sử dụng now()phương thức của nó :
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à:2021-11-07T09:05:48.840370Hãy tự mình thử »
Chữ “T” trong ví dụ trên được dùng để phân tách ngày tháng với thời gian. Bạn có thể sử dụng DateTimeFormatterlớp có ofPattern()phương thức trong cùng một gói để định dạng hoặc phân tích cú pháp 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ờ:
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à:Before Formatting: 2021-11-07T09:05:48.840831Hãy tự mình thử »
After Formatting: 07-11-2021 09:05:48
Các ofPattern()phương pháp 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à thời gian trong một định dạng khác nhau. Ví dụ:
Lượt xem : 225
This is excellent news!
Haven't seen the build yet, I'll look now.
Checking the build now