In this article, we will understand how to display dates of calendar year in different format. Java does not have a built-in Date class, but we can import the java.time package to work with the date and time API. The package includes many date and time classes.
Below is a demonstration of the same −
Suppose our input is −
Run the program
The desired output would be −
The first date format is:2022-03-17T23:37:37.623304800 The second date format is:17/03/2022 The third date format is:Thursday, 17 Mar 2022
Algorithm
Step 1 - START Step 2 - Declare an object of LocalDateTime namely date. Step 3 - Define the values. Step 4 - Define different date time formats using DateTimeFormatter objects Step 5 - Display the different date time formats Step 6 - Stop
Example 1
Here, we bind all the operations together under the ‘main’ function.
import java.time.*; import java.time.format.DateTimeFormatter; public class Demo { public static void main(String[] args){ System.out.println("The required packages have been imported"); LocalDateTime date = LocalDateTime.now(); System.out.println("A LocalDateTime object has been defined"); System.out.println("\nThe first date format is:" +date); DateTimeFormatter date_format_1 = DateTimeFormatter.ofPattern("dd/MM/yyyy"); String formattedDate_1 = date.format(date_format_1); System.out.println("\nThe second date format is:" +formattedDate_1); DateTimeFormatter date_format_2 = DateTimeFormatter.ofPattern("EEEE, dd MMM yyyy"); String formattedDate_2 = date.format(date_format_2); System.out.println("\nThe third date format is:" +formattedDate_2); } }
Output
The required packages have been imported A LocalDateTime object has been defined The first date format is:2022-03-29T08:53:19.809 The second date format is:29/03/2022 The third date format is:Tuesday, 29 Mar 2022
Example 2
Here, we encapsulate the operations into functions exhibiting object oriented programming.
import java.time.*; import java.time.format.DateTimeFormatter; public class Demo { static void print_date_format(LocalDateTime date){ DateTimeFormatter date_format_1 = DateTimeFormatter.ofPattern("dd/MM/yyyy"); String formattedDate_1 = date.format(date_format_1); System.out.println("\nThe second date format is:" +formattedDate_1); DateTimeFormatter date_format_2 = DateTimeFormatter.ofPattern("EEEE, dd MMM yyyy"); String formattedDate_2 = date.format(date_format_2); System.out.println("\nThe third date format is:" +formattedDate_2); } public static void main(String[] args){ System.out.println("The required packages have been imported"); LocalDateTime date = LocalDateTime.now(); System.out.println("A LocalDateTime object has been defined"); System.out.println("\nThe first date format is:" +date); print_date_format(date); } }
Output
The required packages have been imported A LocalDateTime object has been defined The first date format is:2022-03-29T08:53:58.155 The second date format is:29/03/2022 The third date format is:Tuesday, 29 Mar 2022