Date format conversion using Java
I am having a date/time value in standard ISO 8601 format such as as 2010-07-26T11:37:52Z.
开发者_高级运维I want date in 26-jul-2010 (dd-mon-yyyy) format. How do I do it?
Construct two SimpleDateFormat objects. The first you parse() the value from into a Date object, the second you use to turn the Date object back into a string, e.g.
try {
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
DateFormat df2 = new SimpleDateFormat("dd-MMM-yyyy");
return df2.format(df1.parse(input));
}
catch (ParseException e) {
return null;
}
Parsing can throw a ParseException so you would need to catch and handle that.
Have you tried using Java's SimpleDateFormat
class? It is included with the android SDK: http://developer.android.com/reference/java/text/SimpleDateFormat.html
I am providing the modern answer. No one should use SimpleDateFormat
anymore.
java.time
Parsing text.
String dateTimeValue = "2010-07-26T11:37:52Z";
OffsetDateTime dateTime = OffsetDateTime.parse(dateTimeValue);
Generating text.
DateTimeFormatter dateFormatter =
DateTimeFormatter.ofPattern(
"dd-MMM-uuuu",
Locale.forLanguageTag("pt-BR")
);
String wantedFormattedDate = dateTime.format(dateFormatter);
Output:
System.out.println(wantedFormattedDate);
26-jul-2010
The month abbreviation in the output depends on the locale provided (Brazilian Portuguese in my example).
I am exploiting the fact that your date-time is in ISO 8601 format, the format that the classes of java.time parse (and also print) as their default, that is, without any explicit formatter.
Avoid the SimpleDateFormat
class used in the other answers. That class is notoriously troublesome and long outdated.
Normally you would not want to convert a date and time from a string in one format to a string in a different format. In your program keep date and time as a date-time object, for example Instant
or OffsetDateTime
. Only when you need to give out a string, format your date into one.
Links
- Oracle tutorial: Date Time explaining how to use java.time.
- Wikipedia article: ISO 8601
精彩评论