This solution skips the old SimpleDateFormat
and Date
and instead uses the newer classes described in JSR-310. They are generally much more programmer-friendly.
String formattedDate = Instant.parse(publishedAt)
.atOffset(ZoneOffset.UTC)
.format(DateTimeFormatter.ofPattern("EEE dd'th' MMM, hh:mm", Locale.ENGLISH));
This prints
Sat 20th May, 06:00
Please note that we have now lost whether the time was in AM or PM. 06:00
could mean 6 AM or 6 PM. You may want to consider once more whether this was what you wanted. If not, just modify the format pattern string in the code to your needs, and ask if in doubt. I am printing the time in UTC time zone, assuming this was what you intended.
You will also notice that I give no explicit format for parsing the string. This is because your string conforms with ISO 8601, which is what the JSR-310 classes “understand” as their default.
This is all very nice when the date is May 20th. What about the following day? We don’t want 21th May
, but 21st
. This is where the JSR-310 classes show one of their real advantages: it is straightforward and safe to get the day of month so we can check whether for instance it’s the 1st, the 2nd or the 21st day of a month:
OffsetDateTime dateTime = Instant.parse(publishedAt).atOffset(ZoneOffset.UTC);
String numberSuffix = "th";
if (dateTime.getDayOfMonth() == 1 || dateTime.getDayOfMonth() == 21
|| dateTime.getDayOfMonth() == 31) {
// print for example 01st or 21st
numberSuffix = "st";
} else if (dateTime.getDayOfMonth() == 2 || dateTime.getDayOfMonth() == 22) {
numberSuffix = "nd";
} else if (dateTime.getDayOfMonth() == 3 || dateTime.getDayOfMonth() == 23) {
numberSuffix = "rd";
}
String formatPattern = "EEE dd'" + numberSuffix + "' MMM, hh:mm";
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern(formatPattern, Locale.ENGLISH);
With this change we can also have a result of
Sun 21st May, 06:00
To use the JSR-310 classes on Android you need to get the ThreeTenABP. I include a couple of links below. For anyone using Java 8 or later, they are built-in in the java.time
package.
Links