java将yyyy-MM-dd HH:mm:ss 转为yyyy-MM-dd
时间: 2023-09-27 15:08:28 浏览: 55
可以使用Java中的SimpleDateFormat类来进行日期格式化。具体的代码如下:
```java
String dateString = "2022-11-11 11:11:11";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = dateFormat.parse(dateString);
dateFormat.applyPattern("yyyy-MM-dd");
String output = dateFormat.format(date);
System.out.println(output);
```
代码中首先定义了一个日期字符串dateString和一个SimpleDateFormat对象dateFormat,dateFormat的格式为"yyyy-MM-dd HH:mm:ss"。
然后使用dateFormat的parse方法将日期字符串解析为Date对象。
接着使用applyPattern方法将dateFormat的格式修改为"yyyy-MM-dd"。
最后使用dateFormat的format方法将Date对象格式化为字符串并输出。
相关问题
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()));
```
java String yyyy-MM-dd HH:mm:ss 转为 yyyy-MM-dd
你可以使用 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。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)