Date conversion in Java
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.
a source to share
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 .
a source to share
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);
}
a source to share
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')
a source to share