Parsing Date Strings into Date Objects
To convert a date string into a Date object, the SimpleDateFormat class provides a parse method. However, if the provided pattern does not match the input date string, a ParseException will be thrown.
Solution
In this case, the input date string includes "Thu" and "Sep," indicating abbreviated day and month names, respectively. The correct pattern should use "EEE" and "MMM" for these elements. Additionally, the locale must be explicitly set to English to avoid locale-specific issues.
The corrected code is:
import java.text.DateFormat; import java.text.SimpleDateFormat; import java.text.ParseException; import java.util.Date; import java.util.Locale; public class DateParser { public static void main(String[] args) throws ParseException { String target = "Thu Sep 28 20:29:30 JST 2000"; DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH); Date result = df.parse(target); System.out.println(result); } }
This code prints the correct Date object, adjusted for the specified timezone:
Thu Sep 28 07:29:30 BOT 2000
Additional Considerations
When parsing date strings, you may also want to consider using "HH" instead of "kk" for the hour pattern, as it represents 24-hour time notation. Refer to the SimpleDateFormat documentation for more information on valid patterns.
The above is the detailed content of How to Parse Date Strings with Abbreviated Day and Month Names?. For more information, please follow other related articles on the PHP Chinese website!