Java 程序以不同格式显示日历年的日期
javacampus interviewserver side programmingprogramming
在本文中,我们将了解如何以不同格式显示日历年的日期。Java 没有内置的 Date 类,但我们可以导入 java.time 包来使用日期和时间 API。该包包含许多日期和时间类。
下面是相同的演示 −
假设我们的输入是 −
Run the program
期望的输出将是 −
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
算法
步骤 1 - 开始 步骤 2 - 声明 LocalDateTime 的对象,即日期。 步骤 3 - 定义值。 步骤 4 - 使用 DateTimeFormatter 对象定义不同的日期时间格式 步骤 5 - 显示不同的日期时间格式 步骤 6 - 停止
示例 1
在这里,我们将所有操作绑定在 ‘main’ 函数下。
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); } }
输出
The required packages have been imported A LocalDateTime object has been defined 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
示例 2
在这里,我们将操作封装成展现面向对象编程的函数。
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); } }
输出
The required packages have been imported A LocalDateTime object has been defined 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