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
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
Check the javadocs for java.text.SimpleDateFormat It describes everything you need.
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);
}
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));
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.