java获得年月日时分秒形式的当前时间,Date类型
时间: 2023-07-09 18:46:23 浏览: 377
您可以使用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按照年月日时分秒打印当前时间
可以使用Java中的Date和SimpleDateFormat类来实现打印当前时间的功能。具体代码如下:
```java
import java.util.Date;
import java.text.SimpleDateFormat;
public class PrintCurrentTime {
public static void main(String[] args) {
// 创建Date对象
Date date = new Date();
// 创建SimpleDateFormat对象,设置时间格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 格式化当前时间
String currentTime = sdf.format(date);
// 输出当前时间
System.out.println("当前时间为:" + currentTime);
}
}
```
输出结果类似于:当前时间为:2021-08-12 15:18:27
阅读全文
相关推荐













