Date conversion in Java

How can I take a string in a format like: 2008-06-02 00:00:00.0

and convert it to 02-Jun-2008

:?

Is there some way to take the original string, convert it to a Date object, and then use a formatter to get the final output (rather than parsing the string yourself)? Thanks!

+2


a source to share


4 answers


You can use SimpleDateFormat

to convert between String

and Date

and vice versa based on the template. Click the API link, you can see the details explained in detail. 4 digit year can be represented yyyy

, with the abbreviation of month 3 symbols may be presented MMM

, etc.

First you need to parse the String

first format into an object Date

:

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

      



Then you need to format Date

in the String

second format:

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

      

Please note that you need to take into account Locale

to get the month to print in English, otherwise it will use the platform's default locale to translate the month.

+7


a source


Use 2 instances of the class SimpleDateFormat

. One to convert your input string to a date and one to convert your date to a string, but in a different format.



Here is an example using SimpleDateFormat .

0


a source


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);
 }

      

0


a source


You can definitely use the SimpleDateFormat class as others have recommended.

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

0


a source







All Articles