Trong bài này, chúng ta sẽ hiểu cách hiển thị ngày năm theo nhiều định dạng khác nhau. Java không có lớp Date tích hợp, nhưng có thể import java.time để làm việc với API ngày giờ.
Dưới đây là minh họa:
Giả sử đầu vào:
Chạy chương trình
Đầu ra mong muốn:
Định dạng 1: 2022-03-17T23:37:37.623304800 Định dạng 2: 17/03/2022 Định dạng 3: Thursday, 17 Mar 2022
Thuật toán
Bước 1 - BẮT ĐẦU Bước 2 - Khai báo đối tượng LocalDateTime tên date. Bước 3 - Định nghĩa giá trị. Bước 4 - Định nghĩa các định dạng ngày giờ dùng DateTimeFormatter. Bước 5 - Hiển thị các định dạng ngày giờ khác nhau. Bước 6 - KẾT THÚC
Ví dụ 1
Gom thao tác dưới hàm 'main'.
import java.time.*;
import java.time.format.DateTimeFormatter;
public class Demo {
public static void main(String[] args){
System.out.println("Các gói cần thiết đã được import");
LocalDateTime date = LocalDateTime.now();
System.out.println("Đối tượng LocalDateTime đã được định nghĩa");
System.out.println("\nĐịnh dạng 1:" + date);
DateTimeFormatter date_format_1 = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String formattedDate_1 = date.format(date_format_1);
System.out.println("\nĐịnh dạng 2:" + formattedDate_1);
DateTimeFormatter date_format_2 = DateTimeFormatter.ofPattern("EEEE, dd MMM yyyy");
String formattedDate_2 = date.format(date_format_2);
System.out.println("\nĐịnh dạng 3:" + formattedDate_2);
}
}
Kết quả
Các gói cần thiết đã được import Đối tượng LocalDateTime đã được định nghĩa Định dạng 1: 2022-03-29T08:53:19.809 Định dạng 2: 29/03/2022 Định dạng 3: Tuesday, 29 Mar 2022
Ví dụ 2
Đóng gói thao tác vào hàm thể hiện OOP.
import java.time.*;
import java.time.format.DateTimeFormatter;
public class Demo {
static void print_date_format(LocalDateTime date){
DateTimeFormatter date_format_1 = DateTimeFormatter.ofPattern("dd/MM/yyyy");
String formattedDate_1 = date.format(date_format_1);
System.out.println("\nĐịnh dạng 2:" + formattedDate_1);
DateTimeFormatter date_format_2 = DateTimeFormatter.ofPattern("EEEE, dd MMM yyyy");
String formattedDate_2 = date.format(date_format_2);
System.out.println("\nĐịnh dạng 3:" + formattedDate_2);
}
public static void main(String[] args){
System.out.println("Các gói cần thiết đã được import");
LocalDateTime date = LocalDateTime.now();
System.out.println("Đối tượng LocalDateTime đã được định nghĩa");
System.out.println("\nĐịnh dạng 1:" + date);
print_date_format(date);
}
}
Kết quả
Các gói cần thiết đã được import Đối tượng LocalDateTime đã được định nghĩa Định dạng 1: 2022-03-29T08:53:58.155 Định dạng 2: 29/03/2022 Định dạng 3: Tuesday, 29 Mar 2022