#JavaInspires
Hi Guys,
Welcome to Java Inspires.
In this post, we will have a program to get/determine day of the week in Java.
First we will see how to get today's day of the week, then we will see how to get day of the week of a particular date.
Here, I have used Java 11 and java.time.LocalDate api which is introduced in Java 8.
Code Snippet:
package com.javainspires; import java.time.LocalDate; /** * * @author #JavaInspires * */ public class JavaBasicMain { public static void main(String[] args) { // To get current day - day of the week LocalDate localDate = LocalDate.now(); String dayOfWeek = localDate.getDayOfWeek().toString(); System.out.println("Today is " + dayOfWeek); // to get particular day - day of the week // we will try 01-01-2021 day of the week LocalDate someDay = LocalDate.of(2021, 01, 01); System.out.println("01-01-2021 is " + someDay.getDayOfWeek().toString()); } }
Output:
Today is THURSDAY 01-01-2021 is FRIDAY
About LocalDate:
public final class LocalDate extends Object
implements Temporal, TemporalAdjuster, ChronoLocalDate, Serializable
A date without a time-zone in the ISO-8601 calendar system, such as 2007-12-03.
LocalDate is an immutable date-time object that represents a date, often viewed as year-month-day. Other date fields, such as day-of-year, day-of-week and week-of-year, can also be accessed. For example, the value "2nd October 2007" can be stored in a LocalDate.
This class does not store or represent a time or time-zone. Instead, it is a description of the date, as used for birthdays. It cannot represent an instant on the time-line without additional information such as an offset or time-zone.
The ISO-8601 calendar system is the modern civil calendar system used today in most of the world. It is equivalent to the proleptic Gregorian calendar system, in which today's rules for leap years are applied for all time. For most applications written today, the ISO-8601 rules are entirely suitable. However, any application that makes use of historical dates, and requires them to be accurate will find the ISO-8601 approach unsuitable.
This is a value-based class; use of identity-sensitive operations (including reference equality (==), identity hash code, or synchronization) on instances of LocalDate may have unpredictable results and should be avoided. The equals method should be used for comparisons.
LocalDate.now()
public static LocalDate now()
Obtains the current date from the system clock in the default time-zone.
This will query the system clock in the default time-zone to obtain the current date.
Using this method will prevent the ability to use an alternate clock for testing because the clock is hard-coded.
Returns:
the current date using the system clock and default time-zone, not null