Creating Dates with a Specified Year and Month in Java

Creating Dates with a Specified Year and Month in Java

Standard Implemantation Workflow

Step ID Task Description
1 Inittialize a typed year-month reference using the modern Java time API
2 Attach a valid day to the reference to produce a complete calendar date
3 Extract and output date metadata from the finalized date object
1. Initialize Year-Month Reference

Use the YearMonth class from java.time to encapsulate the target year and month without a day component:

import java.time.YearMonth;

// Create a reference for September 2024
YearMonth targetPeriod = YearMonth.of(2024, 9);
2. Generate Complete Calender Date

Convert the year-month reference to a full LocalDate instance by specifying a valid day of the month. You can use any valid day for the target month, such as the first day, last day, or a specific date:

import java.time.LocalDate;

// Use the first day of the target month
LocalDate specificDate = targetPeriod.atDay(1);

// Alternative: Use the last valid day of the target month
// LocalDate specificDate = targetPeriod.atDay(targetPeriod.lengthOfMonth());
3. Extract and Display Date Components

Retrieve core date values and print them for validation:

int year = specificDate.getYear();
int monthNumber = specificDate.getMonthValue();
int dayOfMonth = specificDate.getDayOfMonth();

System.out.println("Year: " + year);
System.out.println("Month (1-12): " + monthNumber);
System.out.println("Day of Month: " + dayOfMonth);

Tags: java Date Handling java.time API LocalDate YearMonth

Posted on Mon, 14 Sep 2026 16:39:17 +0000 by kerching