tags:

views:

3055

answers:

4

Hi,

I want to convert String to Date in different Format.

For example,

I am getting from user,

String fromDate = "19/05/2009"; (dd/MM/yyyy)

I want to convert this fromDate as a Date object of "yyyy-MM-dd" format

How can I do this?

Thanks in Advance

+5  A: 

Check the javadocs for java.text.SimpleDateFormat It describes everything you need.

Matt
+1  A: 

Use the SimpleDateFormat-class:

private Date parseDate(String date, String format) throws ParseException
{
 SimpleDateFormat formatter = new SimpleDateFormat(format);
 return formatter.parse(date);
}

Usage:

Date date = parseDate("19/05/2009", "dd/MM/yyyy");

For efficiency, you would want to store your formatters in a hashmap. The hashmap is a static member of your util class.

private static Map<String, SimpleDateFormat> hashFormatters = new HashMap<String, SimpleDateFormat>();

public static Date parseDate(String date, String format) throws ParseException
{
 SimpleDateFormat formatter = hashFormatters.get(format);

 if (formatter == null)
 {
  formatter = new SimpleDateFormat(format);
  hashFormatters.put(format, formatter);
 }

 return formatter.parse(date);
}
Agora
CAVEAT!! The idea is good, but the implementation is not. DateFormats must not be stored statically, because they are not thread-safe! If they are used from more than one thread (and this is always risky with statics). FindBugs contains a detector for this (which I happened to contribute initially, after I got bitten. See http://dschneller.blogspot.com/2007/04/calendar-dateformat-and-multi-threading.html :-))
Daniel Schneller
Your blog entry is an interesting read :-) What if the parseDate-method itself i synchronized? The problem though is that it would probably slow the code down...
Agora
As long as the parseDate method was the only method accessing the map, synchronizing it would work. However this would - as you say - introduce a bottleneck.
Daniel Schneller
+17  A: 

Take a look at SimpleDateFormat. The code goes something like this:

SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");

String reformattedStr = myFormat.format(fromUser.parse(inputString));
Michael Myers
+3  A: 

While SimpleDateFormat will indeed work for your needs, additionally you might want to check out Joda Time, which is apparently the basis for the redone Date library in Java 7. While I haven't used it a lot, I've heard nothing but good things about it and if your manipulating Dates extensively in your projects it would probably be worth looking into.

James McMahon
Joda is good! Yay!
Steve McLeod