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!
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.
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.
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);
}
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')
精彩评论