การจัดรูปแบบและการแปลงวันที่
การจัดรูปแบบและการแปลงวันที่เป็นทักษะสำคัญในการทำงานกับข้อมูลวันที่ในรูปแบบต่าง ๆ ในแบบฝึกหัดนี้ คุณจะได้จัดรูปแบบวันที่และแปลง String ให้เป็น LocalDate
คลาสที่จำเป็นทั้งหมดจาก java.time ถูก import ไว้ให้แล้ว
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Input/Output และ Streams ใน Java
คำแนะนำการฝึกหัด
- ดึงวันที่ปัจจุบัน
- กำหนด
DateTimeFormatterด้วย patterndd-MM-yyyy - จัดรูปแบบวันที่ปัจจุบันโดยใช้ formatter ที่กำหนด
- แปลง string วันที่โดยใช้ formatter ที่กำหนดไว้
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
public class DateExample {
public static void main(String[] args) {
// Get current date
LocalDate date = ____;
System.out.println("Current date in default format: " + date);
// Define format with pattern dd-MM-yyyy
DateTimeFormatter formatter = DateTimeFormatter.____("dd-MM-yyyy");
// Format and print date
System.out.println(date.____(formatter));
// Parse a text into a string
LocalDate parseDate = LocalDate.____("2025-02-10");
System.out.println("Parse the text into date: " + parseDate);
}
}