Explain Codes LogoExplain Codes Logo

What is the easiest way to get the current day of the week in Android?

java
date-and-time
localdate
datetimeformatter
Alex KataevbyAlex Kataev·Dec 26, 2024
TLDR

First up, a fast and simple approach to get the day of the week in Android:

int today = java.util.Calendar.getInstance().get(java.util.Calendar.DAY_OF_WEEK);

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:

import java.time.LocalDate; import java.time.DayOfWeek; DayOfWeek day = LocalDate.now().getDayOfWeek();

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.

  1. Spruce up your build.gradle(Module: app) file.
android { ... compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } coreLibraryDesugaringEnabled true } dependencies { coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.0.9' ... }
  1. Now LocalDate and DayOfWeek will be at your service.
DayOfWeek day = LocalDate.now().getDayOfWeek();

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:

import java.time.format.DateTimeFormatter; import java.time.format.TextStyle; import java.util.Locale; DayOfWeek day = LocalDate.now().getDayOfWeek(); String dayName = day.getDisplayName(TextStyle.FULL, Locale.getDefault());

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:

try { DayOfWeek day = LocalDate.now().getDayOfWeek(); // Easy like Sunday morning 🎵 } catch (DateTimeException ex) { Log.e("DateError", "Error fetching the current day of the week", ex); // It's probably Monday 😫 }

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:

switch (day) { case SATURDAY: case SUNDAY: highlightWeekendTasks(); // 😎 Easy mode. break; default: highlightWeekdayTasks(); // 😱 Boss fights. }