String format(Date date) | 按照指定的格式,把Date日期转化为符合模式的字符串。 |
parse(String obj) | 把文本格式化为日期 |
下面示例演示:
public class Demo03DataFormat {
public static void main(String[] args) throws ParseException {
// 使用DateFormat类中的format方法,把日期格式化为文本
//String format(Date date) 按照指定的格式,把Date日期转化为符合模式的字符串
demo01();
System.out.println("================");//分割线
demo02();
}
public static void demo01(){
//1.创建SimpleDateFormat对象,构造方法中传递指定的模式
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//2.调用SimpleDateFormat对象中的方法format,按照构造方法指定的模式,把Date日期格式化为符合模式的字符串/
Date date=new Date();
String format = sdf.format(date);
System.out.println(format);
System.out.println(date);
}
//使用DateFormat类中的parse方法,把文本格式化为日期
public static void demo02() throws ParseException {
//1.创建SimpleDateFormat对象,构造方法中传递指定的模式
SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
//parse在此会报错,两个解决办法:1.使用throws抛出异常。2.使用try...catch...处理
Date parse = sdf.parse("2022年01月22日 16时34分51秒");
System.out.println(parse);
}
}
java.util.Date常用的两个方法