What is the easiest way to get the current day of the week in Android?
Solution 1:
The Java Calendar
class works.
Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_WEEK);
switch (day) {
case Calendar.SUNDAY:
// Current day is Sunday
break;
case Calendar.MONDAY:
// Current day is Monday
break;
case Calendar.TUESDAY:
// etc.
break;
}
For much better datetime handling consider using the Java 8 time API:
String day = LocalDate.now().getDayOfWeek().name()
To use this below Android SDK 26 you'll need to enable Java 8 desugaring in build.gradle:
android {
defaultConfig {
// Required when setting minSdkVersion to 20 or lower
multiDexEnabled true
}
compileOptions {
// Flag to enable support for the new language APIs
coreLibraryDesugaringEnabled true
// Sets Java compatibility to Java 8
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.0.9'
}
More information on Android's Java 8 support: https://developer.android.com/studio/write/java8-support
Solution 2:
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
// 3 letter name form of the day
System.out.println(new SimpleDateFormat("EE", Locale.ENGLISH).format(date.getTime()));
// full name form of the day
System.out.println(new SimpleDateFormat("EEEE", Locale.ENGLISH).format(date.getTime()));
Result (for today):
Sat Saturday
UPDATE: java8
LocalDate date = LocalDate.now();
DayOfWeek dow = date.getDayOfWeek();
System.out.println("Enum = " + dow);
String dayName = dow.getDisplayName(TextStyle.FULL, Locale.ENGLISH);
System.out.println("FULL = " + dayName);
dayName = dow.getDisplayName(TextStyle.FULL_STANDALONE, Locale.ENGLISH);
System.out.println("FULL_STANDALONE = " + dayName);
dayName = dow.getDisplayName(TextStyle.NARROW, Locale.ENGLISH);
System.out.println("NARROW = " + dayName);
dayName = dow.getDisplayName(TextStyle.NARROW_STANDALONE, Locale.ENGLISH);
System.out.println("NARROW_STANDALONE = " + dayName);
dayName = dow.getDisplayName(TextStyle.SHORT, Locale.ENGLISH);
System.out.println("SHORT = " + dayName);
dayName = dow.getDisplayName(TextStyle.SHORT_STANDALONE, Locale.ENGLISH);
System.out.println("SHORT_STANDALONE = " + dayName);
Result (for today):
Enum = SATURDAY
FULL = Saturday
FULL_STANDALONE = Saturday
NARROW = S
NARROW_STANDALONE = 6
SHORT = Sat
SHORT_STANDALONE = Sat
Solution 3:
Calendar.getInstance().get(Calendar.DAY_OF_WEEK)
or
new GregorianCalendar().get(Calendar.DAY_OF_WEEK);
Just the same as in Java, nothing particular to Android.
Solution 4:
Java 8 datetime
API
made it so much easier :
LocalDate.now().getDayOfWeek().name()
Will return you the name of the day as String
Output : THURSDAY