Write a Java program to display the dates in the specified formats


This program demonstrates how to display dates and times in different formats using the Java 8 Date/Time API. Here are the explanations of the key points in the program:

  • LocalDate d = LocalDate.now();: This creates a new LocalDate object that represents the current date.
  • System.out.println("Default Format of Local Date : "+d); : This displays the default format of the LocalDate object. The default format is yyyy-mm-dd.
  • System.out.println("Specific Format : "+d.format(DateTimeFormatter.ofPattern("d::MMM::uuuu")));: This displays the LocalDate object in a specific format using the DateTimeFormatter class. The ofPattern method is used to create a formatter that specifies the desired format.
  • LocalDateTime dt = LocalDateTime.now();: This creates a new LocalDateTime object that represents the current date and time.
  • System.out.println("Default Format of Local DateTime : "+dt); : This displays the default format of the LocalDateTime object. The default format is yyyy-mm-ddThh:mm:ss.
  • System.out.println("Specific Format : "+dt.format(DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss")));: This displays the LocalDateTime object in a specific format using the DateTimeFormatter class.
  • Instant timestamp = Instant.now();: This creates a new Instant object that represents the current timestamp. This object is not used in the program, but it demonstrates how to get the current timestamp.

Source Code

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
class Display_Dates
{
 
	public static void main(String[] args)
	{		
		//Local Date
		LocalDate d = LocalDate.now();
		System.out.println("Default Format of Local Date : "+d);
		System.out.println("Specific Format : "+d.format(DateTimeFormatter.ofPattern("d::MMM::uuuu")));
		//Local DateTime
		LocalDateTime dt = LocalDateTime.now();
		System.out.println("Default Format of Local DateTime : "+dt);
		System.out.println("Specific Format : "+dt.format(DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss")));
   		Instant timestamp = Instant.now();		
	}
}

Output

Default Format of Local Date : 2022-11-05
Specific Format : 5::Nov::2022
Default Format of Local DateTime : 2022-11-05T13:27:39.381466500
Specific Format : 5::Nov::2022 13::27::39

Example Programs