![](https://i-blog.csdnimg.cn/blog_migrate/53f8dde6c1ff87cff364a6b64aea3ccc.jpeg)
![](https://i-blog.csdnimg.cn/blog_migrate/88110cc54cf00e2fc50b73ee6ad03718.jpeg)
// 使用format()方法将日期转换为指定格式的文本
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd HH:mm");
SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 创建Date对象,表示当前时间
Date now = new Date();
// 调用format()方法,将日期转换为字符串并输出
System.out.println(sdf1.format(now) );
System.out.println(sdf2.format(now));
System.out.println(sdf3.format(now));
// 使用parse()方法将文本转换为日期
String d = "2014-6-1 21:05:36";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 调用parse()方法,将字符串转换为日期 //
调用 SimpleDateFormat 对象的 parse() 方法时可能会出现转换异常,即 ParseException ,因此需要进行异常处理
Date date = sdf.parse(d);
System.out.println(date);
结果现在并不推荐使用Date,有设计缺陷?没有考虑时区?
![](https://i-blog.csdnimg.cn/blog_migrate/20fb2e989b4fda0460b26b1f305a3dc0.jpeg)
![](https://i-blog.csdnimg.cn/blog_migrate/e3428f92842c064cc624cf59cffd4f1e.jpeg)
Calendar c = Calendar.getInstance();
// 将Calendar对象转换为Date对象
Date date = c.getTime();
// 创建SimpleDateFormat对象,指定目标格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 将日期转换为指定格式的字符串
String now = sdf.format(date);
System.out.println("当前时间:" + now);