Many programming languages are used for programming for Android. Since you mentioned the outdated SimpleDateFormat
class, I am assuming that you are using Java, if not the language then at least the Java platform/runtime. Then I warmly recommend java.time
, the modern Java date and time API. For example, using Java:
LocalDate today = LocalDate.now(ZoneId.of("Asia/Manila"));
LocalDate backThen = LocalDate.of(1995, Month.JUNE, 10);
Since it is never the same date everywhere on the planet, make sure you specify your desired time zone for getting today’s date. A LocalDate
is a date without time of day.
To get only the month for use in your program:
Month m = today.getMonth();
Running my code just now this returned Month.APRIL
. Month
is an enum with the 12 months of the Gregorian calendar.
If you wanted to print just the month to the user, your format pattern string should just contain only MMM
(or MMMM
for full month name):
DateTimeFormatter monthFormatter
= DateTimeFormatter.ofPattern("MMM", Locale.forLanguageTag("fil-PH"));
System.out.println(backThen.format(monthFormatter));
This printed:
Hun
I didn’t know June was Hunyo in Philippinese. I know now. Supply a different locale to get the month name in a different language.
And yes, very many tutorials and other pages still float around from when we used SimpleDateFormat
and its now long outdated friends. Your best bet is to ignore them.
Question: Can I use java.time on Android?
Yes, java.time
works nicely on older and newer Android devices. It just requires at least Java 6.
- In Java 8 and later and on newer Android devices (from API level 26, I’m told) the modern API comes built-in.
- In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
- On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from
org.threeten.bp
with subpackages.
Links