How can I parse a date like '2012-08-22 11:55:38
to '8 of August'
I tried with formateador = new SimpleDateFormat("d MMM");
But I'm getting an 'Unparseable date' exception.
Hope you can help me. Thanks
You parse from a string to a Date
. You can then format from a Date
to a string using a different pattern. Currently, given the code you've shown us, it looks like you're trying to parse the value "2012-08-22 11:55:38" with a SimpleDateFormat
expecting the pattern "d MMM", which it clearly doesn't comply to. You should have something like:
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
Locale.US);
// TODO: Set the time zone appropriately
Date date = inputFormat.parse(inputText);
SimpleDateFormat outputFormat = new SimpleDateFormat("d MMM", targetLocale);
// TODO: Set the time zone appropriately
String outputText = outputFormat.format(date);
Note that if you're doing any significant amount of date/time work in Java, you should look into Joda Time , which is a much better date/time API.
This should work (if I understand what you are asking):
String s = "2012-08-22 11:55:38";
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date dt = fmt.parse(s);
DateFormat output = new SimpleDateFormat("d 'of' MMMM", Locale.US);
System.out.println(output.format(dt)); //prints 22 of August
You are having problem while parsing the date from the input string.
"2012-08-22 11:55:38" is in "yyyy-MM-dd HH:mm:ss" format, which you should use to first parse the date from the input string.
Then once you have a Date
object, you can format the date in the required format.
If I get your question correct, you try to parse the first string to a date and then format the resulted date to the seconds string. If this is true then see the code below:
SimpleDateFormat f1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat f2 = new SimpleDateFormat("dd 'of' MMMM");
try {
java.util.Date date = f1.parse("2012-08-22 11:55:38");
System.out.println(f2.format(date));
} catch (ParseException ex) {
ex.printStackTrace();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.