tags:

views:

72

answers:

3

hi can any one please help me on how to convert from 10/21/2009 to Wed Oct 21 18:48:12 UTC+0530 2009 in my java class

+3  A: 
String dateString = new SimpleDateFormat("dd/MM/yyyy").parse(d).toString();

Here you'll get more information: http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html

Sinuhe
+4  A: 

Quite frankly, you can't convert 10/21/2009 to Wed Oct 21 18:48:12 UTC+0530 for the simple reason that the first date does contain neither time nor timezone information.

Martin Hohenberg
At least, not without making some assumptions.
tvanfosson
Well, that's true.
Sinuhe
+2  A: 

You don't specify if the original value (10/21/2009) is a date object or a string, I'm going to assume that it is in fact a String, so you first need to parse the string and convert it to a date object using the SimpleDateFormatter class

import java.text.SimpleDateFormatter;

SimpleDateFormatter sdf = new SimpleDateFormatter("MM/dd/yyyy");
Date d = sdf.parse("10/21/2009");

Once you have a date object, you can just call toString() on it which will get you the string you want, or create another SimpleDateFormatter object with the pattern that you want (check the javadocs) and then call format().

There's a couple of things you should be aware of regarding the DateFormatter classes available in the JDK

  • If the string can not be parsed, the parse method will throw an exception, you will need to handle the exception accordingly
  • The date formatter classes available in the JDK are not threadsafe. Don't create a private/protected/public member variable of these types, instead create the formatters/parsers in the methods where you need them
Chris Gow
If you want to reuse a SimpleDateFormatter, you could store it in a ThreadLocal. Personally, I avoid the DateFormatter classes, and use Joda Time instead.
NamshubWriter