java 以date的格式输出当前时间 到年月日 时分秒
时间: 2023-08-07 15:28:01 浏览: 90
可以使用Java自带的Date类来获取当前日期时间,并使用SimpleDateFormat类将其格式化为指定的格式,例如:
```
import java.util.Date;
import java.text.SimpleDateFormat;
public class Main {
public static void main(String[] args) {
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDateTime = sdf.format(now);
System.out.println(formattedDateTime);
}
}
```
运行该代码,可以得到类似于如下格式的输出:
```
2022-01-10 17:10:26
```
需要注意的是,Date类已经过时,推荐使用Java8中的LocalDateTime类来代替。
相关问题
Java格式化时间到年月日时分秒
可以使用Java中的SimpleDateFormat类来格式化时间,示例代码如下:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatExample {
public static void main(String[] args) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String formattedDate = formatter.format(date);
System.out.println("Formatted Date: " + formattedDate);
}
}
```
运行以上代码,将会输出当前时间的格式化结果,示例输出如下:
```
Formatted Date: 2021-08-23 15:20:45
```
其中,SimpleDateFormat的构造函数中的字符串参数表示时间的格式化规则,"yyyy"表示年份,"MM"表示月份,"dd"表示日期,"HH"表示小时(24小时制),"mm"表示分钟,"ss"表示秒。详细的格式化规则可以参考Java官方文档。
java将当前时间转为年月日时分秒
可以使用Java中的SimpleDateFormat类来将当前时间转换为年月日时分秒格式。以下是示例代码:
```
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTimeExample {
public static void main(String[] args) {
Date currentDate = new Date();
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = dateformat.format(currentDate);
System.out.println("当前时间:" + formattedDate);
}
}
```
在上面的代码中,我们首先获取当前时间Date对象。然后创建一个SimpleDateFormat对象,指定要转换的日期时间格式。最后使用format()方法将Date对象转换为字符串形式的日期时间。输出结果将会是类似于“2021-11-11 14:25:30”的格式化日期时间字符串。
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)