คลาส java.text.SimpleDateFormat ใช้จัดรูปแบบและแปลงสตริง↔วันที่
Pattern Letters สำหรับ Year
| Letter | Component | Example |
|---|---|---|
| y | Year (ปีปฏิทิน) | 2005, 96 |
| Y | Week Year (ปีของสัปดาห์ - ใช้กับ w) | 2005, 96 |
ความแตกต่าง y vs Y:
- y = Calendar Year (ปีปกติ 1 มกราคม - 31 ธันวาคม)
- Y = Week Year (ปีตามสัปดาห์ ISO อาจแตกต่างที่ช่วงต้น/ปลายปี)
ตัวอย่างการจัดรูปแบบปี
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Example {
public static void main(String args[]) throws ParseException {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/dd/MM");
Date date = formatter.parse("2007/25/06");
System.out.println("Date value: " + date);
formatter = new SimpleDateFormat("y:G");
date = formatter.parse("1920:BC");
System.out.println("Date value: " + date);
formatter = new SimpleDateFormat("D-M-Y");
date = formatter.parse("25-05-1989");
System.out.println("Date value: " + date);
}
}
ผลลัพธ์
Date value: Mon Jun 25 00:00:00 IST 2007 Date value: Sun Jan 01 00:00:00 IST 1920 Date value: Sun Jan 01 00:00:00 IST 1989
ตัวอย่างเพิ่มเติม: แสดงปีในรูปแบบต่างๆ
import java.text.SimpleDateFormat;
import java.util.Date;
public class YearFormatExample {
public static void main(String args[]) {
Date now = new Date();
SimpleDateFormat fmt1 = new SimpleDateFormat("yyyy"); // 2024
SimpleDateFormat fmt2 = new SimpleDateFormat("yy"); // 24
SimpleDateFormat fmt3 = new SimpleDateFormat("Y"); // Week year
SimpleDateFormat fmt4 = new SimpleDateFormat("yyyy-'W'ww"); // 2024-W01
System.out.println("Full year: " + fmt1.format(now));
System.out.println("Short year: " + fmt2.format(now));
System.out.println("Week year: " + fmt3.format(now));
System.out.println("Year-Week: " + fmt4.format(now));
}
}
⚠️ หมายเหตุ重要
SimpleDateFormat เป็น Legacy API และ ไม่ Thread-Safe สำหรับโปรเจกต์ Java 8+ ควรใช้ DateTimeFormatter แทน:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy");
String year = LocalDate.now().format(formatter); // "2024"