java获得年月日时分秒形式的当前时间,Date类型
时间: 2023-07-09 14:46:23 浏览: 125
您可以使用Java中的`java.util.Date`类来获取当前时间,并使用`SimpleDateFormat`类来将时间格式化为年月日时分秒的形式。下面是一个示例代码:
```
import java.util.Date;
import java.text.SimpleDateFormat;
public class CurrentDateTimeExample {
public static void main(String[] args) {
Date currentDate = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = formatter.format(currentDate);
System.out.println("Current Date and Time: " + formattedDate);
}
}
```
这个代码会输出当前的年月日时分秒形式的时间,例如:
```
Current Date and Time: 2021-09-12 14:30:45
```
请注意,`java.util.Date`类在Java 8及以后版本已经过时,建议使用`java.time`包中的类来替代。
相关问题
java获得年月日时分秒形式的当前时间
您可以使用Java中的`java.time`包中的`LocalDateTime`类来获取当前时间,并使用`DateTimeFormatter`类来将时间格式化为年月日时分秒的形式。下面是一个示例代码:
```
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class CurrentDateTimeExample {
public static void main(String[] args) {
LocalDateTime currentDateTime = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = currentDateTime.format(formatter);
System.out.println("Current Date and Time: " + formattedDateTime);
}
}
```
这个代码会输出当前的年月日时分秒形式的时间,例如:
```
Current Date and Time: 2021-09-12 14:30:45
```
您可以根据需要修改日期时间格式的模式字符串来自定义日期时间格式。
java将当前时间转为Date类型的年月日时分秒
您可以使用Java中的`SimpleDateFormat`类将当前时间转为指定格式的字符串,然后再将字符串转为`Date`类型。以下是示例代码:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
// 创建SimpleDateFormat对象,指定日期格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 获取当前时间
Date now = new Date();
// 将当前时间转为指定格式的字符串
String nowStr = sdf.format(now);
System.out.println("当前时间:" + nowStr);
try {
// 将字符串转为Date类型
Date date = sdf.parse(nowStr);
// 输出Date类型的年月日时分秒
System.out.println("年:" + (date.getYear() + 1900));
System.out.println("月:" + (date.getMonth() + 1));
System.out.println("日:" + date.getDate());
System.out.println("时:" + date.getHours());
System.out.println("分:" + date.getMinutes());
System.out.println("秒:" + date.getSeconds());
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
输出结果如下:
```
当前时间:2022-05-16 16:23:30
年:2022
月:5
日:16
时:16
分:23
秒:30
```