SimpleDateFormat有如下方法:
·构造方法:public SimpleDateFormat(String pattern),传递格式;
·将Date转换为String:public final String format(Date date);
·将String转换为Date:public Date parse(String sourse)throws ParseException
范例1:将日期格式化显示(Date 转为 String)
import java.text.SimpleDateFormat;
import java.util.Date;
public class Demo {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(date));
}
}
============分割线============
范例2:将字符串转为日期
import java.text.SimpleDateFormat;
import java.util.Date;
public class Demo {
public static void main(String[] args) throws Exception {
String str = "2018-05-07 14:50:20";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = sdf.parse(str);
System.out.println(date);
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/acdc9415b9aed27fa683e9ee61007b88.png)