写一个java方法将yyyy-MM-dd HH:mm:ss时间格式转化为yyyy-MM-dd格式
时间: 2023-04-10 10:02:43 浏览: 68
可以使用 SimpleDateFormat 类来实现这个功能,代码如下:
```java
public static String formatDate(String dateTimeStr) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = formatter.parse(dateTimeStr);
formatter.applyPattern("yyyy-MM-dd");
return formatter.format(date);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
```
其中,dateTimeStr 是待转换的时间字符串,返回值是转换后的日期字符串。
相关问题
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 方法将其格式化成字符串,最后输出即可。
yyyy-MM-dd'T'HH:mm:ss转yyyy-MM-dd HH:mm:ss
要将yyyy-MM-dd'T'HH:mm:ss格式的日期时间转换为yyyy-MM-dd HH:mm:ss格式,可以按照以下步骤进行转换:
1. 首先,将输入的字符串解析为日期时间对象。可以使用Java中的SimpleDateFormat类来实现。示例代码如下:
```java
String inputDateTime = "yyyy-MM-dd'T'HH:mm:ss";
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date = inputFormat.parse(inputDateTime);
```
2. 接下来,将日期时间对象格式化为目标格式的字符串。同样使用SimpleDateFormat类,示例代码如下:
```java
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String outputDateTime = outputFormat.format(date);
```
最后,outputDateTime就是转换后的yyyy-MM-dd HH:mm:ss格式的日期时间字符串。