使用 Java 中的 Date() 函数获取当前时间
发布时间:2023-06-05 03:47:49
Java 中的 Date() 函数是用于获取当前时间的一种方法。Date() 函数会返回当前系统时间,并将其表示为相对于 1970 年 1 月 1 日 00:00:00 GMT 的毫秒数。
下面是一些用于获取当前时间的 Java 代码示例:
1. 使用 Date() 函数获取当前时间
Date currentDate = new Date();
System.out.println("Current date is: " + currentDate);
上述代码会输出当前日期和时间的字符串表示形式,例如:
Current date is: Fri Jun 11 15:16:53 GMT+08:00 2021
2. 将 Date 对象格式化为指定的字符串格式
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = dateFormat.format(new Date());
System.out.println("Formatted date is: " + formattedDate);
上述代码会将当前日期和时间格式化为指定的字符串格式,例如:
Formatted date is: 2021-06-11 15:16:53
3. 使用 Calendar 类获取当前时间
Calendar calendar = Calendar.getInstance();
Date currentDate = calendar.getTime();
System.out.println("Current date is: " + currentDate);
上述代码会使用 Calendar 类获取当前时间,与 Date() 函数相似,输出当前日期和时间的字符串表示形式。
4. 获取当前时间的毫秒数
long currentTimeMillis = System.currentTimeMillis();
System.out.println("Current time in milliseconds is: " + currentTimeMillis);
上述代码会输出当前时间的毫秒数,例如:
Current time in milliseconds is: 1623407513644
总之,Java 中的 Date() 函数是获取当前时间的一种常用方法,可以用于对日期和时间进行各种操作和处理。在实际应用中,我们需要根据具体需求来选择合适的方式来获取当前时间。
