java中String转Date
在Java中,可以使用SimpleDateFormat类将String类型转换为Date类型。以下是一个示例:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
String dateString = "2021-05-15 10:30:00";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = format.parse(dateString);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
在上面的示例中,我们首先定义了一个日期字符串"2021-05-15 10:30:00",然后创建了一个SimpleDateFormat对象,并指定日期格式为"yyyy-MM-dd HH:mm:ss"。接下来,我们使用parse()方法将字符串转换为Date对象,并打印出来。输出结果为Sat May 15 10:30:00 GMT+08:00 2021。
需要注意的是,SimpleDateFormat是线程不安全的,使用时需要注意线程安全问题。如果在多线程环境中使用,可以考虑使用ThreadLocal来解决线程安全问题
原文地址: http://www.cveoy.top/t/topic/i1Zp 著作权归作者所有。请勿转载和采集!