字符串转换为时间格式,按照这个格式yyyy-MM-dd HH:mm:ss 使用java
时间: 2024-04-29 20:24:51 浏览: 12
可以使用SimpleDateFormat类中的parse()方法将字符串转换为时间格式:
```java
String strDate = "2021-09-15 10:30:00";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = format.parse(strDate);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
```
输出结果为:Wed Sep 15 10:30:00 CST 2021
相关问题
将长时间格式时间转换为字符串 yyyy-MM-dd HH:mm:ss java
可以使用 SimpleDateFormat 类来将长时间格式时间转换为字符串,具体代码如下:
long time = System.currentTimeMillis(); // 获取当前时间的长整型表示
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 创建 SimpleDateFormat 对象,指定时间格式
String strTime = sdf.format(new Date(time)); // 将长整型时间转换为字符串
System.out.println(strTime); // 输出转换后的字符串
java 字符串转时间格式 yyyy-MM-dd HH:mm:ss
你使用`SimpleDateFormat`类来将字符串转换为时间格式。以下是一个示例代码:
```java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
String str = "2022-01-01 12:34:56";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = dateFormat.parse(str);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
```
在上述代码中,我们首先定义了一个字符串`str`,它表示要转换的时间。然后,我们创建一个`SimpleDateFormat`对象,并指定时间的格式为`yyyy-MM-dd HH:mm:ss`。接下来,我们使用`parse`方法将字符串转换为`Date`对象,并打印输出结果。
注意:在使用`parse`方法时,如果字符串与指定的时间格式不匹配,会抛出`ParseException`异常,因此需要使用`try-catch`块进行异常处理。