Java parsing a date like Thursday, May 29, 2008 1:45 PM into a more usable format?
I need to parse dates like Thursday, May 29, 2008 1:45 PM
for a current project and don't have much time get it done. I realize I can write some custom parser but that would take a while, I've tried a few date parsers I've found but none are working for this, I would greatly appreciate if anyone ha开发者_Python百科s any advice. I mainly just need to capture the month, day and year as integers, like:
int month = 5;
int date = 29;
int year = 2008
thanks for any advice
Use SimpleDateFormat
. According to the docs, the pattern of your date string would be "EEEE, MMMM d, yyyy h:mm a"
. You can create a SimpleDateFormat
object using this pattern and use it to parse strings:
DateFormat dateParser = new SimpleDateFormat("EEEE, MMMM d, yyyy h:mm a");
Date myDate = dateParser.parse("Thursday, May 29, 2008 1:45 PM");
As BalusC states in the comments, if your code will be used on machines that do not have English set as the primary language, the above snippet will fail. To avoid this, specify English explicitly when constructing the parser.
DateFormat dateParser = new SimpleDateFormat("EEEE, MMMM d, yyyy h:mm a", Locale.ENGLISH);
To pull individual values out of the date object, you'll need to construct a Calendar
:
Calendar calendar = Calendar.getInstance(); // or Calendar.getInstance(Locale.ENGLISH);
calendar.setTime(myDate);
You can then ask it for the values you want.
int month = calendar.get(Calendar.MONTH);
int date = calendar.get(Calendar.DATE);
int year = calendar.get(Calendar.YEAR);
public Date dateFormat(String inputTimestamp) {
DateFormat dateFormat = new SimpleDateFormat("E, MMM dd, yyyy hh:mm a", Locale.US);
Date date = null;
try {
date = dateFormat.parse(inputTimestamp);
} catch (ParseException ex) {
System.err.println("There was a parse exception :"+ex.getMessage());
}
return date;
}
Use SimpleDateFormat to format the date.
http://download.oracle.com/javase/1.4.2/docs/api/java/text/DateFormat.html#parse(java.lang.String)
精彩评论