日期格式转换遇java.text.ParseException报错,求解决方案
Hey Kumar, let's break down what's going on here and get that date conversion working right.
First, let's clarify the mismatch: your input date is the ISO 8601 format 2014-05-13T23:58:30.457, but the error says it can't parse Tue May 13 23:58:30 IST 2014. That suggests you might have mixed up the parsing and formatting steps in your code—like trying to use the output pattern to parse the input string, or vice versa.
Here's the step-by-step fix:
1. Use the correct pattern for parsing your ISO date
To parse 2014-05-13T23:58:30.457, you need a formatter that matches the ISO structure. For older Java versions (pre-8), use SimpleDateFormat with the pattern yyyy-MM-dd'T'HH:mm:ss.SSS. For Java 8+, the newer java.time API is more reliable and avoids timezone bugs.
2. Format to the desired IST string (if that's your goal)
Once you've parsed the ISO date into a date object, you can format it into the Tue May 13 23:58:30 IST 2014 style using a separate formatter with the pattern EEE MMM dd HH:mm:ss zzz yyyy.
Example Code (Java pre-8):
// Parse the ISO input date String isoInput = "2014-05-13T23:58:30.457"; SimpleDateFormat isoParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS"); Date date = isoParser.parse(isoInput); // Format to the IST string output SimpleDateFormat istFormatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH); istFormatter.setTimeZone(TimeZone.getTimeZone("IST")); String formattedDate = istFormatter.format(date); System.out.println(formattedDate); // Outputs: Tue May 13 23:58:30 IST 2014
Better Alternative (Java 8+ with java.time):
The legacy SimpleDateFormat has known issues with timezones and thread safety. Use the modern API instead:
String isoInput = "2014-05-13T23:58:30.457"; // Parse ISO date to LocalDateTime LocalDateTime localDateTime = LocalDateTime.parse(isoInput); // Assign IST timezone (use Asia/Kolkata for exact timezone ID) ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.of("Asia/Kolkata")); // Format to desired string DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH); String formattedDate = zonedDateTime.format(formatter); System.out.println(formattedDate); // Outputs: Tue May 13 23:58:30 IST 2014
Common Mistakes to Check:
- Reversed Parsing/Formatting: Make sure you're not trying to parse the human-readable IST string with the ISO pattern, or formatting the ISO string with the IST pattern.
- Locale Settings: Without specifying
Locale.ENGLISH, the formatter might use your system's default locale, which could produce non-English day/month names that don't match the error message's format. - Timezone Configuration: Ensure the timezone is set correctly when formatting to IST—using
Asia/Kolkatais more precise thanISTwhich can refer to multiple timezones.
内容的提问来源于stack exchange,提问作者Kumar Harsh

