java获得年月日时分秒形式的当前时间
时间: 2023-07-09 17:46:23 浏览: 52
您可以使用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中的`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
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class GetCurrentTime {
public static void main(String[] args) {
// 获取当前时间
Calendar calendar = Calendar.getInstance();
// 格式化时间
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = dateFormat.format(calendar.getTime());
// 输出当前时间
System.out.println("当前时间为:" + currentTime);
}
}
```
运行以上代码,将输出当前时间的年月日时分秒形式,例如:
```
当前时间为:2022-08-31 15:30:00
```