时间日期没有秒如何转成日期格式
时间: 2024-03-01 14:56:17 浏览: 17
如果你有一个时间日期字符串,但是它不包含秒数,你可以使用Java中的SimpleDateFormat类对其进行格式化。下面是一个示例代码:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateDemo {
public static void main(String[] args) throws Exception {
// 时间日期字符串
String datetime = "2020-11-01 10:20";
// 创建SimpleDateFormat对象,指定日期格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
// 将时间日期字符串解析成Date对象
Date date = sdf.parse(datetime);
// 将Date对象格式化成字符串,输出日期部分
String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(date);
System.out.println(dateStr);
}
}
```
在上面的示例代码中,我们首先定义了一个时间日期字符串"2020-11-01 10:20",然后创建了一个SimpleDateFormat对象sdf,指定日期格式为"yyyy-MM-dd HH:mm"。接着,我们使用SimpleDateFormat的parse方法将时间日期字符串解析成Date对象。最后,我们将Date对象格式化成字符串,输出日期部分,即"2020-11-01"。
需要注意的是,SimpleDateFormat的parse方法会抛出ParseException异常,需要进行异常处理。同时,如果时间日期字符串中没有包含年月日等信息,你也无法将其转换成日期格式。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)