Java中的Date函数如何获取当前系统时间并进行格式化输出?
发布时间:2023-09-27 00:49:35
在Java中,可以使用Date类来获取当前系统时间。Date类位于java.util包中,是Java提供的用于处理日期和时间的类。
要获取当前系统时间,可以先创建一个Date对象,然后调用其无参构造函数即可。代码如下所示:
Date currentDate = new Date();
接下来,可以使用SimpleDateFormat类来进行时间格式化。SimpleDateFormat位于java.text包中,是Java提供的用于日期和时间格式化的类。
SimpleDateFormat类的构造函数可以传入一个时间格式字符串作为参数。常用的时间格式字符串有以下几种:
- "yyyy-MM-dd":表示年-月-日,例如2021-12-31;
- "yyyy/MM/dd":表示年/月/日,例如2021/12/31;
- "MM/dd/yyyy":表示月/日/年,例如12/31/2021;
- "HH:mm:ss":表示时:分:秒,例如23:59:59;
- "yyyy-MM-dd HH:mm:ss":表示年-月-日 时:分:秒,例如2021-12-31 23:59:59。
代码如下所示:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = dateFormat.format(currentDate);
System.out.println(formattedDate); // 输出格式化后的时间字符串
此代码将使用"yyyy-MM-dd HH:mm:ss"格式来格式化当前系统时间,并将格式化后的时间字符串输出到控制台。
完整示例代码如下所示:
import java.util.Date;
import java.text.SimpleDateFormat;
public class CurrentTimeExample {
public static void main(String[] args) {
// 获取当前系统时间
Date currentDate = new Date();
// 格式化输出当前系统时间
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = dateFormat.format(currentDate);
System.out.println(formattedDate);
}
}
运行程序,将会输出当前系统时间的格式化字符串,例如"2021-12-31 23:59:59"。
通过上述方法,可以轻松地获取当前系统时间并进行格式化输出。
