java 获取当前时间的字符串,格式为2023-12-31 12:16:40
时间: 2024-03-13 11:43:15 浏览: 33
可以使用Java的SimpleDateFormat类来获取当前时间的指定格式的字符串。
示例代码如下:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class CurrentTime {
public static void main(String[] args) {
// 获取当前时间
Date date = new Date();
// 设置日期格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 格式化日期
String currentTime = sdf.format(date);
// 输出当前时间的字符串
System.out.println("当前时间:" + currentTime);
}
}
```
输出结果:
```
当前时间:2022-11-17 14:50:00
```
在示例代码中,通过`new Date()`获取当前时间,然后使用`SimpleDateFormat`类的`format()`方法将日期格式化成指定格式的字符串。其中`"yyyy-MM-dd HH:mm:ss"`表示日期格式,其中`yyyy`表示年份,`MM`表示月份,`dd`表示日,`HH`表示小时,`mm`表示分钟,`ss`表示秒。
相关问题
java获取当前日期 格式为yyyy-MM-dd HH:mm:ss
你使用Java的`SimpleDateFormat`类来获取当前日期并按照指定格式进行格式化。以下是一个示例代码:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
// 创建日期格式化对象
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 获取当前日期时间
Date currentDate = new Date();
// 格式化日期时间
String formattedDate = sdf.format(currentDate);
// 输出结果
System.out.println("当前日期时间: " + formattedDate);
}
}
```
这段代码中,我们创建了一个`SimpleDateFormat`对象,并指定日期格式为"yyyy-MM-dd HH:mm:ss"。然后,通过`new Date()`获取当前日期时间,再使用`format()`方法将其格式化为指定格式的字符串。最后,将格式化后的日期时间打印出来。
运行代码后,你将得到类似以下的输出结果:
```
当前日期时间: 2022-03-15 10:30:45
```
请注意,输出结果将根据你运行代码的时间而有所不同。
Java获取yyyy-MM-dd HH:mm:ss格式的当前时间
在Java中获取当前时间并格式化成 yyyy-MM-dd HH:mm:ss 的字符串可以使用如下代码:
```
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
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(formattedDate);
}
}
```
其中,SimpleDateFormat 类可以将 Date 类型的日期格式化成字符串,而 "yyyy-MM-dd HH:mm:ss" 则是指定的日期格式。这里先创建了一个 SimpleDateFormat 对象 formatter,指定日期格式为 "yyyy-MM-dd HH:mm:ss",然后获取当前时间的 Date 对象并调用 formatter 对象的 format 方法将其格式化成字符串,最后输出即可。
相关推荐
![text/x-java](https://img-home.csdnimg.cn/images/20210720083646.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)