SimpleDateFormat日期和文本之间相互转换

           java.text.DateFormat 是日期/时间格式化子类的抽象类,我们可以通过他的子类SimpleDateFormat在Date对象与String对象之间进行来回转换

格式化:按照指定的格式,从Date对象转换为String对象。

解析:按照指定的格式,从String对象转换为Date

DateFormat类的常用方法有:
public String format(Date date) :将Date对象格式化为字符串。
public Date parse(String source) :将字符串解析为Date对象。

把Date对象转换成String

使用format方法的代码为:


public class Demo03 {
public static void main(String[] args) {
  Date date = new Date();
// 创建日期格式化对象,在获取格式化对象时可以指定风格
DateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
String str = df.format(date);
System.out.println(str); // 2008年1月23日
}
}

把String对象转换成Date

使用parse方法的代码为:

扫描二维码关注公众号,回复: 5554731 查看本文章

public class Demo04 {
public static void main(String[] args) throws ParseException {
DateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
String str = "2018年12月11日";
Date date = df.parse(str);
System.out.println(date); // Tue Dec 11 00:00:00 CST 2018
}
}

猜你喜欢

转载自www.cnblogs.com/zhangxiaozhen/p/10544868.html