Formatting a calendar date

scarhand picture scarhand · May 27, 2012 · Viewed 57.6k times · Source

I just want the date to show up like so:

Saturday, May 26, 2012 at 10:42 PM

Here's my code so far:

Calendar calendar = Calendar.getInstance();
String theDate = calendar.get(Calendar.MONTH) + " " + calendar.get(Calendar.DAY_OF_MONTH) + " " + calendar.get(Calendar.YEAR);

lastclick.setText(getString(R.string.lastclick) + " " + theDate);

This shows the numbers of the month, day, and year, but there's got to be a better way of doing this? Isn't there some simple way of doing this like using PHP's date() function?

Answer

creemama picture creemama · May 27, 2012
Calendar calendar = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("EEEE, MMMM d, yyyy 'at' h:mm a");
System.out.println(format.format(calendar.getTime()));

Running the above code outputs the current time (e.g., Saturday, May 26, 2012 at 11:03 PM).

See the Android documentation for SimpleDateFormat for more information.

The format specification of SimpleDateFormat is similar to that of PHP's date function:

echo date("l, M j, Y \a\\t g:i A");

You're right. Compared to the Java code, the PHP code is much more succinct.