tags:

views:

142

answers:

5

I have dates in text format of the form dd-mmm-yy or d-mmm-y, where months are abbreviations in letters (for example, 4-Nov-09 or 12-Dec-05, etc...) I would like to parse it to produce a java.util.Date object.

Could this be achieved by leveraging the java.text.DateFormat class? Or is there another easy way of doing this?

+4  A: 

You may need to use the SimpleDateFormat for parsing custom formats. This article explains the details of formatting.

"d-MMM-yyyy" corresponds to 4-Nov-2009
Vincent Ramdhanie
this takes a date and formats it to a string, i need the oposite, any other examples?
David Menard
You want to parse a string to date, so use the `parse` method.
BalusC
It does both ways. Use parse() to go from String to Date
Vincent Ramdhanie
figured it out, thanks
David Menard
Note: SimpleDateFormat is not synchronized. I discovered this when I was supporting a Tomcat application that crashed due to two threads playing with the same memory area simultaneously. If you use SimpleDateFormat in a web application then ensure you instantiate a new object for each web request.
PP
+1  A: 

You can do it with java.text.SimpleDateFormat. Click the link, you'll see all patterns.

For 1-2 digit days you can use the d pattern. For 3-character month abbreviations you can use the MMM pattern. For 2 digit years you can use the yy pattern.

So the following should do:

String dateString = "4-Nov-09";
SimpleDateFormat sdf = new SimpleDateFormat("d-MMM-yy");
Date date = sdf.parse(dateString);
BalusC
A: 

Check out SimpleDateFormat

examples

Omnipresent
+1  A: 

Whatever you do, please use a Locale. That way, you'll still get reasonable results when the input comes in with a month name in French.

shoover
+1: the thing to keep in mind.
BalusC
+2  A: 

SimpleDateFormat is the class normally used for this. Note that this class is not thread-safe (somewhat counter-intuitively) and if you're using this in a threaded context, then investigating Joda and its DateTimeFormatter is worthwhile.

Brian Agnew