Java函数实现获取当前系统时间并格式化输出的方法?
发布时间:2023-07-03 17:37:31
在Java中,可以使用java.util.Date类和java.text.SimpleDateFormat类来实现获取当前系统时间并格式化输出的方法。
首先,我们需要导入java.util.Date和java.text.SimpleDateFormat类:
import java.util.Date; import java.text.SimpleDateFormat;
然后,可以创建一个方法来获取当前系统时间并进行格式化输出:
public class CurrentTimeFormatter {
public static void main(String[] args) {
// 获取当前系统时间
Date currentTime = new Date();
// 创建SimpleDateFormat对象,并设置日期时间格式
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 使用SimpleDateFormat对象格式化当前系统时间,并将结果输出
String formattedTime = formatter.format(currentTime);
System.out.println(formattedTime);
}
}
在上面的代码中,我们首先创建一个Date对象来获取当前系统时间。然后,我们创建一个SimpleDateFormat对象,通过传入指定的日期时间格式字符串来设置格式。在上面的例子中,我们使用了"yyyy-MM-dd HH:mm:ss"格式,表示年-月-日 时:分:秒。最后,我们调用format()方法将Date对象进行格式化,并将结果以字符串形式输出。
运行以上代码,将会输出一个格式化后的当前系统时间,例如:2021-06-01 12:34:56。
需要注意的是,SimpleDateFormat类中还有许多其他的格式化选项和方法,例如可以设置时区、指定时区、指定 AM/PM 等等。你可以根据自己的需求来选择合适的格式化方式。另外,还可以使用Calendar类来获取当前系统时间,并对时间进行操作。以上就是一种获取当前系统时间并格式化输出的方法,希望能对你有所帮助。
