Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

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.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.