Write a Java Program to Parse individual components of date from a string


This Java program takes a date string in the format "yyyy-MM-dd" and converts it to a LocalDate object using the java.time.LocalDate class. It then extracts the day, month, and year from the LocalDate object and prints them to the console. Here's an explanation of the code:

  • import java.util.Date;: This imports the java.util.Date class, which is not used in this program.
  • import java.time.Month;: This imports the java.time.Month enum, which represents the months of the year.
  • import java.time.LocalDate;: This imports the java.time.LocalDate class, which represents a date without time information.
  • class Components_DateString: This defines a class named Components_DateString.
  • public static void main(String args[]): This is the entry point of the program. It declares a public static method named main that takes an array of strings as an argument.
  • String dt = "2021-12-07";: This creates a String variable named dt and assigns it the value "2021-12-07", which represents a date in the format "yyyy-MM-dd".
  • LocalDate lDate = LocalDate.parse(dt); : This parses the dt string as a LocalDate object.
  • int d = lDate.getDayOfMonth();: This obtains the day of the month from the LocalDate object and stores it in the d variable.
  • Month m = lDate.getMonth();: This obtains the month of the year from the LocalDate object as a Month enum value and stores it in the m variable.
  • int y = lDate.getYear();: This obtains the year from the LocalDate object and stores it in the y variable.
  • System.out.println("Day : " + d);: This prints the string "Day : " followed by the value of the d variable to the console.
  • System.out.println("Month: " + m);: This prints the string "Month: " followed by the value of the m variable to the console.
  • System.out.println("Year : " + y);: This prints the string "Year : " followed by the value of the y variable to the console.

Source Code

import java.util.Date;
import java.time.Month;
import java.time.LocalDate;
class Components_DateString
{
	public static void main(String args[])
	{
		String dt = "2021-12-07";
		LocalDate lDate = LocalDate.parse(dt);
 
		int d = lDate.getDayOfMonth();
		Month m = lDate.getMonth();
		int y = lDate.getYear();
 
		System.out.println("Day  : " + d);
		System.out.println("Month: " + m);
		System.out.println("Year : " + y);
	}
}

Output

Day  : 7
Month: DECEMBER
Year : 2021

Example Programs