java String yyyy-MM-dd HH:mm:ss 转为 yyyy-MM-dd
时间: 2023-07-19 09:40:49 浏览: 133
你可以使用 SimpleDateFormat 类来将字符串 yyyy-MM-dd HH:mm:ss 转换为 yyyy-MM-dd 格式的日期字符串。示例代码如下:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) throws Exception {
String strDate = "2021-10-12 15:30:00";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf1.parse(strDate);
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
String strDate2 = sdf2.format(date);
System.out.println(strDate2);
}
}
```
这段代码的输出结果为:2021-10-12。
相关问题
java string yyyy-mm-dd hh:mm:ss 转 string yyyy-mm-dd
可以使用 Java 中的 SimpleDateFormat 类来将字符串格式化成另一种格式。以下是将 "yyyy-MM-dd HH:mm:ss" 格式的字符串转换为 "yyyy-MM-dd" 格式的代码示例:
```
String dateString = "2022-05-28 13:20:30";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = dateFormat.parse(dateString);
dateFormat.applyPattern("yyyy-MM-dd");
String newDateString = dateFormat.format(date);
System.out.println(newDateString);
```
输出结果为:
```
2022-05-28
```
这样就成功将 "yyyy-MM-dd HH:mm:ss" 格式的字符串转换为 "yyyy-MM-dd" 格式的字符串了。
java日期yyyy-mm-dd HH:mm:ss正则表达式
以下是Java日期格式化为yyyy-mm-dd HH:mm:ss的正则表达式:
```java
String regex = "\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}";
```
该正则表达式匹配的日期格式为:yyyy-mm-dd HH:mm:ss。其中,\\d表示数字,{4}表示4个数字,{2}表示2个数字。正则表达式中的“-”和“:”表示这些字符必须在日期中出现。
如果要将其他格式的日期转换为yyyy-mm-dd HH:mm:ss格式,可以使用SimpleDateFormat类。例如,将当前日期格式化为yyyy-mm-dd HH:mm:ss格式的代码如下所示:
```java
String format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
System.out.println(simpleDateFormat.format(new Date()));
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)