Calendar c = Calendar.getInstance();
Toast.makeText(this, " " + c.DAY_OF_MONTH + " " + c.MONTH + " " + c.YEAR, Toast.LENGTH_LONG).show();
// 輸出:5 2 1 (而非預期的 17 4 2013)
c.DAY_OF_MONTH、c.MONTH、c.YEAR 是 Calendar 類的靜態常量(int 值),分別為 5、2、1,代表欄位索引,而非當前日期數值。
Calendar c = Calendar.getInstance();
int day = c.get(Calendar.DAY_OF_MONTH); // 17
int month = c.get(Calendar.MONTH); // 3 (0-based,4月)
int year = c.get(Calendar.YEAR); // 2013
// 月份需 +1 顯示
String dateStr = String.format("%02d-%02d-%04d", day, month + 1, year);
Toast.makeText(this, dateStr, Toast.LENGTH_LONG).show();
// 輸出:17-04-2013
| 常量 | 值 | 含義 |
|---|---|---|
| Calendar.DAY_OF_MONTH | 5 | 欄位索引:日 |
| Calendar.MONTH | 2 | 欄位索引:月(0-11) |
| Calendar.YEAR | 1 | 欄位索引:年 |
// Java 8+ / Android API 26+
LocalDate now = LocalDate.now();
String formatted = now.format(DateTimeFormatter.ofPattern("dd-MM-yyyy"));
// 或
int day = now.getDayOfMonth();
int month = now.getMonthValue(); // 1-12
int year = now.getYear();
優點:不可變、執行緒安全、API 直觀、無 0-based 月份陷阱。
c.DAY_OF_MONTH → ✅ c.get(Calendar.DAY_OF_MONTH)c.MONTH 直接顯示 → ✅ c.get(Calendar.MONTH) + 1new Date() 格式化 → ✅ SimpleDateFormat / DateTimeFormatterCalendar.getInstance() 使用預設時區/語言環境 → 指定 TimeZone / Locale 若需國際化