Java开发中经常涉及到时间Date与字符串String之间的相互转换,如何转换呢?主要是通过SimpleDateFormat类来操作的。
下面代码说明:
1.日期转字符串格式化:
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(sdf.format(date));
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(date));
sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
System.out.println(sdf.format(date));
打印结果:
2018-07-28
2018-07-28 10:37:06
2018年07月28日 10:37:06
2.字符串转换日期格式:
String string = "2018-07-28 10:39:01";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.parse(string));
打印结果:
Sat Jul 28 10:39:01 CST 2018
构造函数中pattern为时间模式,参考下图: