【Java】Date与字符串String 相互转化的方法

Date -> String

理解Date类和Date转 String的方法

可以参考我写的另一篇文章 – Java用Date类获取当前时间戳、时间戳的格式转换方法,就不在多赘述了


String -> Date

方法与Date转String非常的类似,需要用到SimpleDateFormat对象(上链接文章也有讲到)的parse()方法,语法是 > Date date = simpleDateFormatObj.parse(String time);

需要注意的是time字符串的时间需要严格与simpleDateFormatObj对象创建时的格式一致,否则会报错,而且如果“不符合现实时间”的字符串也会报错,例如“2017-15-30”

实例代码

//接收String类型时间的格式
SimpleDateFormat stringToDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//输出Date类型时间的字符串格式
SimpleDateFormat dateToStringFormat = new SimpleDateFormat("yyyy年MM月dd日E");

try {
	Date today = stringToDateFormat.parse("2018-12-22 15:34:32");
	System.out.println(dateToStringFormat.format(today));
} catch (ParseException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}

结果输出为 ‘2018年12月22日星期六’

猜你喜欢

转载自blog.csdn.net/SeasonSoy/article/details/82662673