java.time
The java.util
Date-Time API and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Solution using java.time
, the modern Date-Time API:
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
public class Main {
public static void main(String[] args) {
LocalDate date = LocalDate.now(ZoneId.of("Asia/Kolkata"));
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.appendText(ChronoField.DAY_OF_MONTH, ordinalMap())
.appendPattern(" MMM. uuuu")
.toFormatter(Locale.ENGLISH);
String output = date.format(dtf);
System.out.println(output);
}
static Map<Long, String> ordinalMap() {
String[] suffix = { "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th" };
Map<Long, String> map = new HashMap<>();
for (int i = 1; i <= 31; i++)
map.put((long) i, String.valueOf(i) + suffix[(i > 3 && i < 21) ? 0 : (i % 10)]);
return map;
}
}
Output:
2nd Oct. 2021
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
Update
A valuable comment from Joachim Sauer:
Since this is tagged as Android, it should be noted that java.time
is
available in Android since 8.0 (Oreo) and most of it can be accessed
even when targeting older versions through desugaring.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.