1. Overview

In this short tutorial, we'll see how to extract the day of the week as a number and as text from a Java date.

2. Problem

Business logic often needs the day of the week. Why? For one, working hours and service levels differ between workdays and weekends. Therefore, getting the day as a number is necessary for a lot of systems. But we also may need the day as a text for display.

So, how do we extract the day of the week from dates in Java?

3. Solution With java.util.Date

java.util.Date has been the Java date class since Java 1.0. Code that started with Java version 7 or lower probably uses this class.

3.1. Day of Week as a Number

First, we extract the day as a number using java.util.Calendar:

public static int getDayNumberOld(Date date) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    return cal.get(Calendar.DAY_OF_WEEK);
}

The resulting number ranges from 1 (Sunday) to 7 (Saturday). Calendar defines constants for this: Calendar.SUNDAY – Calendar.SATURDAY.

3.2. Day of Week as Text

Now we extract the day as text. We pass in a Locale to determine the language:

public static String getDayStringOld(Date date, Locale locale) {
    DateFormat formatter = new SimpleDateFormat("EEEE", locale);
    return formatter.format(date);
}

This returns the full day in your language, such as “Monday” in English or “Montag” in German.

4. Solution With java.time.LocalDate

Java 8 overhauled date and time handling and introduced java.time.LocalDate for dates. Therefore, Java projects that only run on Java versions 8 or higher should use this class!

4.1. Day of Week as a Number

Extracting the day as a number is trivial now:

public static int getDayNumberNew(LocalDate date) {
    DayOfWeek day = date.getDayOfWeek();
    return day.getValue();
}

The resulting number still ranges from 1 to 7. But this time, Monday is 1 and Sunday is 7! The day of the week has its own enum — DayOfWeek. As expected, the enum values are MONDAY – SUNDAY.

4.2. Day of Week as Text

Now we extract the day as text again. We also pass in a Locale:

public static String getDayStringNew(LocalDate date, Locale locale) {
    DayOfWeek day = date.getDayOfWeek();
    return day.getDisplayName(TextStyle.FULL, locale);
}

Just as with java.util.Date, this returns the full day in the chosen language.

5. Conclusion

In this article, we extracted the day of the week from Java dates. We saw how to return both a number and a text using java.util.Date and java.time.LocalDate.

As always, the code is available over on GitHub.

Java bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

>> CHECK OUT THE COURSE
Comments are closed on this article!