Java program to get first Friday in a month



In this article, we'll explore how to get the first Friday of any given month in Java. The program will use Java's LocalDate class and TemporalAdjusters to automatically calculate the first Friday based on the input date. We will walk through how this works step by step and see how the code performs this task.

Problem Statement

Write a program in Java to get the first Friday in a month. Below is a demonstration of the same ?

Input

Current date = 2019-04-01

Output

Current date = 2019-04-01
First Friday date = 2019-04-05

Steps to get the first Friday in a month

Following are the steps to get the first Friday in a month ?

  • Import the necessary classes from java.time package.
  • Create a date and set a date representing the first day of a particular month.
  • Find the first Friday by using Java's TemporalAdjusters.firstInMonth() method with DayOfWeek.FRIDAY to determine the first Friday of that month.
  • Output the result by printing both the current date and the calculated first Friday.

Java program to get the first Friday in a month

Below is the Java program to get the first Friday in a month ?

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.TemporalAdjusters;
public class Demo {
   public static void main(String[] args) {
      LocalDate date = LocalDate.of(2019, Month.APRIL, 1);
      System.out.println("Current date = "+date);
      LocalDate firstFriday = date.with(TemporalAdjusters.firstInMonth(DayOfWeek.FRIDAY));
      System.out.println("First Friday date = "+firstFriday);
   }
}

Output

Current date = 2019-04-01
First Friday date = 2019-04-05

Code Explanation

The program starts by setting a specific date, in this case, April 1st, 2019 using LocalDate.of(). Then, it uses TemporalAdjusters.firstInMonth(DayOfWeek.FRIDAY) to adjust the date and find the first Friday of the month. This method scans the month from the start date and returns the first Friday. The results, including the initial date and the calculated first Friday, are printed.

Updated on: 2024-09-29T02:47:00+05:30

683 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements