What is the easiest way to get the current day of the week in Android?
First up, a fast and simple approach to get the day of the week in Android:
The today
variable will contain a value from 1 (Sunday) to 7 (Saturday). For a more modern approach, you could consider using the LocalDate
class:
This code gives you a DayOfWeek
enumeration representing the current day.
Java 8: The way of the future
If you're using Java 8 or newer, there's a sleeker way to deal with dates and times, using desugaring for older Android versions.
- Spruce up your
build.gradle(Module: app)
file.
- Now
LocalDate
andDayOfWeek
will be at your service.
Localization and format: Because everyone doesn't read dates the same
Upon getting the day of the week, it's time to think about how you'll present this data to your users. Use java.time.format.DateTimeFormatter
and java.text.SimpleDateFormat
for displaying the day of the week in a user-friendly manner:
This gives you the name of the day, like "Monday" or "Tuesday", in the device's locale.
Try, catch: Code that survives the unexpected
While dealing with date and time, you would want your app to handle any problem that might crop up. Add in some defensive coding:
More than just a date: User experience matters
Your app's users won't care about an int showing day of the week. Instead, think about how you can make this information useful and engaging for them:
Was this article helpful?