輸入字符串
Wed Oct 12 2016 00:00:00 GMT+0800 (中國標准時間)
目標格式
2016-10-12
解析難點
- 包含時區文本
GMT+0800 和括號內中文說明,標準 SimpleDateFormat 無法直接解析。
- 月份縮寫
Oct 需 Locale.ENGLISH。
完整代碼
String dateString = "Wed Oct 12 2016 00:00:00 GMT+0800 (中國標准時間)";
// 1. 清理干擾字符
dateString = dateString.replace("GMT", "").replaceAll("\\(.*\\)", "").trim();
// 2. 定義解析格式(注意 Locale.ENGLISH)
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss Z", Locale.ENGLISH);
// 3. 解析為 Date 對象
Date date = sdf.parse(dateString);
// 4. 格式化輸出
String result = new SimpleDateFormat("yyyy-MM-dd").format(date);
System.out.println(result); // 2016-10-12
關鍵點
Z 模式匹配 +0800 格式時區偏移。
HH 24小時制,原字符串用 00:00:00 應用 HH 而非 hh。
- Java 8+ 建議使用
DateTimeFormatter + ZonedDateTime 替代老 API。