Earlier I posted the following question: How can I convert this date in Java?
But now I would like to know how I can convert this string into a date/time.
2010-03-15T16:34:46Z
For example: 03/15/10
UPDATED:
String pattern = "MM/dd/yy 'at' HH:mm";
Date date = new Date();
开发者_运维问答 try {
date = new SimpleDateFormat(pattern).parse(q.getUpdated_at());
} catch (ParseException e) {
e.printStackTrace();
}
dateText.setText(new SimpleDateFormat("MM/dd/yy 'at' hh:mma").format(date));
Gives me a result like:
Mon Mar 15 16:34:50 MST 2010
How can I format it to be
03/15/10 at 4:34PM
?
Both SimpleDateFormat
and joda-time DateTimeFormat
can parse this, using this pattern:
String pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'";
For example:
Date date = new SimpleDateFormat(pattern).parse(dateString);
And (joda-time):
DateTimeFormatter dtf = DateTimeFormat.forPattern(pattern);
DateTime dateTime = dtf.parseDateTime(s);
Update
You have 2 date formats involved - one for parsing the input, and one for formatting the output. So:
dateText.setText(new SimpleDateFormat("MM/dd/yy 'at' hh:mma").format(date));
(Of course, for the sake of optimization, you can instantiate the SimpleDateFormat
only once, and reuse it)
In a nutshell, you want to convert a date in a string format to a date in another string format. You have:
2010-03-15T16:34:46Z
and you want
03/15/10 at 4:34PM
You don't want to end up using java.util.Date
object as you initially implied in your question. You also don't want to use its toString()
since that returns a fixed format as definied in its javadoc.
The answer of Bozho still applies. Use java.text.SimpleDateFormat
. First, you need to parse the date in string format into a Date
object so that you can format it back into another string format.
// First parse string in pattern "yyyy-MM-dd'T'HH:mm:ss'Z'" to date object.
String dateString1 = "2010-03-15T16:34:46Z";
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").parse(dateString1);
// Then format date object to string in pattern "MM/dd/yy 'at' h:mma".
String dateString2 = new SimpleDateFormat("MM/dd/yy 'at' h:mma").format(date);
System.out.println(dateString2); // 03/15/10 at 4:34PM
If you want to format output string, change following line in your code
dateText.setText(date.toString());
to
dateText.setText(String.format("%1$tm/%1$td/%1$ty at %1$tl:%1$tM%1$Tp", date));
精彩评论