在本文中,我们将了解如何显示当前日期和时间。 Java没有内置的Date类,但是我们可以导入java.time包来使用日期和时间API。该包包含许多日期和时间类。
下面是相同的演示 -
假设我们的输入是 -
Run the program
登录后复制
期望的输出是 -
The current date and time is: 2022/03/17 23:43:17
登录后复制
算法
Step 1 - START
Step 2 - Declare an object of LocalDateTime namely date.
Step 3 - Define the values.
Step 4 - Define a date time format using DateTimeFormatter objects
Step 5 - Display the date and time using a specific formats
Step 6 - Stop
登录后复制
示例 1
这里,我们将所有操作绑定到“main”函数下。
import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;
public class Demo {
public static void main(String[] args) {
System.out.println("The required packages have been imported");
System.out.println("A LocalDateTime object has been defined");
DateTimeFormatter date_time = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
System.out.println("nThe current date and time is: " +date_time.format(now));
}
}
登录后复制
输出
The required packages have been imported
A LocalDateTime object has been defined
The current date and time is: 2022/03/17 23:43:17
登录后复制
示例 2
在这里,我们将操作封装到展示面向对象编程的函数中。
import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;
public class Demo {
static void Date_time(DateTimeFormatter date_time){
LocalDateTime now = LocalDateTime.now();
System.out.println("nThe current date and time is: " +date_time.format(now));
}
public static void main(String[] args) {
System.out.println("The required packages have been imported");
System.out.println("A LocalDateTime object has been defined");
DateTimeFormatter date_time = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
Date_time(date_time);
}
}
登录后复制
输出
The required packages have been imported
A LocalDateTime object has been defined
The current date and time is: 2022/03/29 08:55:28
登录后复制
以上就是Java程序显示当前日期和时间的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!