In this article, we will see how to get day of the week in Java starting from version 8 and with java.util.Date. Which has been used in earlier versions of Java 8.
Although the most common would be to use java.time.LocalDate, there are still many applications running on older versions of Java, so we will go through these two ways of obtaining the day of the week with Java
Retrieve day of week with java.util.Date
java.util.Date appeared a few years ago with the first version of Java. To obtain the day of the week, we can return it as a number or in text format. Let’s see both approaches:
To obtain the day of the week as a number from a date with java.util.Date, we will rely on java.util.Calendar:
public int dayofWeek(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(Calendar.DAY_OF_WEEK); }
Now let’s return the day of the week as text, i.e., Monday or Tuesday. For this, we will also pass the Locale.
public String getDayOfWeek(Date date, Locale locale) { DateFormat formatter = new SimpleDateFormat("EEEE", locale); return formatter.format(date); }
Day of the week with java.time.LocalDate
Starting from version 8 of Java, working with dates became much more convenient and easy thanks to java.time.LocalDate.
In this section, we will see how quick and easy it is to obtain the day of the week both in numeric and text format.
Obtaining the day of the week as numeric is done through a method provided by the java.time API. The result is a value between 1 and 7, with 1 being Monday.
public int dayofWeek(LocalDate date) { DayOfWeek day = date.getDayOfWeek(); return day.getValue(); }
On the other hand, to obtain the day of the week in text, we can do the following:
public String getDayOfWeek(LocalDate date, Locale locale) { DayOfWeek day = date.getDayOfWeek(); return day.getDisplayName(TextStyle.FULL, locale); }
DayOfWeek is a class of java.time that provides us with an enum with the days so that we can operate with that class to obtain the day in text format..
Conclusion
In this article, we have seen how to get day of the week in Java, in text and numeric format, for versions of Java before and after version 8.
If you need more information, you can leave us a comment or send an email to refactorizando.web@gmail.com You can also contact us through our social media channels on Facebook or twitter and we will be happy to assist you!!