views:

190

answers:

4

How can I take a string in a format such as: 2008-06-02 00:00:00.0 and convert it to: 02-Jun-2008?

Can I somehow take the original string, convert it to a Date object, then use a formatter to get the final output (rather than parsing the string myself)? Thanks!

+7  A: 

You can use SimpleDateFormat to convert between a String and a Date object and vice versa based on a pattern. Click the API link, you'll see patterns being explained in detail. A 4-digit year can be represented with yyyy, a 3-character month abbreviation can be represented with MMM and so on.

First you need to parse the String of the first format into a Date object:

SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date date = sdf1.parse(inputString);

Then you need to format the Date into a String of the second format:

SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);
String outputString = sdf2.format(date);

Note that you need to take the Locale into account as well to get the month to be printed in English, else it will use the platform's default locale to translate the month.

BalusC
For the outputString line, shouldn't it be `sdf2.format(date)`?
justkt
@justkt, that was already fixed during an early edit :) `Ctrl+C Ctrl+V` is evil.
BalusC
Sorry I missed the edit.
justkt
A: 

Use 2 instances of SimpleDateFormat class. One for converting your input string to date and second to convert date back to string but in another format.

Here is an example of using SimpleDateFormat.

Roman
A: 
DateFormat startFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
DateFormat endFormat = new SimpleDateFormat("dd-MM-yyyy");
String outputString = null;
try {
    Date date = startFormat.parse(inputString);
    outputString = endFormat.format(date);
 } catch(ParseException pe) {
     throw new IllegalArgumentException(inputString + " is not properly formated.", pe);
 }
justkt
A: 

You can definitely use SimpleDateFormat class like others have recommended.

Another suggestion if it applies in your case. If you are getting this data from a sql query you can also use to_char() method to format it in the query itself. For example: to_char(column_name,'DD-MON-YYYY')

CoolBeans