從外部來源(如 RSS、API)獲取 mm/dd/yyyy 格式日期字串,需存入 SQLite 日期欄位(建議存儲為 TEXT 格式 yyyy-MM-dd 或 INTEGER 存時間戳)。
String input = "12/31/2023"; // mm/dd/yyyy
SimpleDateFormat srcFormat = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
SimpleDateFormat dstFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
try {
Date date = srcFormat.parse(input);
String dbFormat = dstFormat.format(date); // "2023-12-31"
// 插入 SQLite
ContentValues values = new ContentValues();
values.put("date_column", dbFormat);
db.insert("table_name", null, values);
} catch (ParseException e) {
Log.e("DATE", "Invalid format: " + input, e);
}
| 符號 | 含義 | 注意 |
|---|---|---|
| MM | 月份(01-12) | 大寫 MM,小寫 mm 代表分鐘 |
| dd | 日期(01-31) | |
| yyyy | 四位年份 | |
| HH | 24制小時 | 若含時間部分 |
| mm | 分鐘 | 小寫 |
避免格式轉換麻煩,統一存儲為 INTEGER 毫秒時間戳:
// 存入
long timestamp = System.currentTimeMillis(); // 或 date.getTime()
values.put("date_column", timestamp);
// 查詢轉換顯示
Cursor c = db.query(...);
long ts = c.getLong(c.getColumnIndex("date_column"));
String display = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date(ts));
優點:排序、範圍查詢(WHERE date BETWEEN ? AND ?)極其高效,無格式歧義。
若堅持存 TEXT 格式 yyyy-MM-dd,可直接用 SQLite 內建函數:
// 查詢今天數據
SELECT * FROM table WHERE date_column = date('now');
// 查詢最近 7 天
SELECT * FROM table WHERE date_column >= date('now', '-7 days');
要求存儲格式嚴格符合 YYYY-MM-DD。
SimpleDateFormat("MM/dd/yyyy"),格式化用 SimpleDateFormat("yyyy-MM-dd")。MM(月) 與 mm(分),常見錯誤來源。INTEGER 時間戳,應用層按需格式化顯示。