使用Java将date类型时间格式的yyyy-MM-dd HH:mm:ss 转为date类型时间格式的yyyy-MM-dd
时间: 2024-01-12 08:03:12 浏览: 30
可以使用Java中的`SimpleDateFormat`类来进行时间格式的转换。具体代码如下:
```java
// 原始时间字符串
String originalTime = "2021-10-28 15:30:45";
// 定义原始时间格式
SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 将原始时间字符串转为Date类型
Date date = originalFormat.parse(originalTime);
// 定义目标时间格式
SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd");
// 将Date类型时间转为目标格式的字符串
String targetTime = targetFormat.format(date);
// 输出目标时间字符串
System.out.println(targetTime);
```
输出结果为:
```
2021-10-28
```
这样就实现了将`date`类型时间格式的`yyyy-MM-dd HH:mm:ss`转为`date`类型时间格式的`yyyy-MM-dd`。
相关问题
java把Date类型转为yyyy-MM-dd HH:mm:ss格式的字符串
要将Java中的Date类型转换为指定格式的字符串,可以使用SimpleDateFormat类。以下是一个示例代码:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateToStringExample {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
}
}
```
在上面的代码中,我们创建了一个SimpleDateFormat对象,并指定了日期格式为"yyyy-MM-dd HH:mm:ss"。然后,使用format()方法将Date对象转换为字符串。
Java new date转为yyyy-mm-dd HH:MM:SS格式
可以使用SimpleDateFormat类来将Java的Date对象转换为指定格式的字符串。
示例代码:
```java
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Date now = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = dateFormat.format(now);
System.out.println(formattedDate);
}
}
```
输出结果:
```
2021-11-18 12:34:56
```
在上面的示例中,我们首先创建了一个Date对象表示当前时间,然后创建了一个SimpleDateFormat对象,指定输出的格式为"yyyy-MM-dd HH:mm:ss",最后调用dateFormat.format方法将Date对象转换为字符串。
相关推荐
![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_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)