有很多时候,我们都需要将日期进行格式化,以便以最合适的形式展现给别人,下面简短的代码可以体验实验效果:
SimpleDateFormat sp1 = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
SimpleDateFormat sp2 = new SimpleDateFormat("yyyy年 mm月 dd日 hh时mm分ss秒");
Date date = new Date();
System.out.println(sp1.format(date));
System.out.println(sp2.format(date));
显示结果:
2021-37-17 08:37:36
2021年 37月 17日 08时37分36秒
从面的结果可以看到具体操作步骤:
1)先准备一个包含yyyy mm dd hh mm ss格式式符在内的你想展示给别人看的最终字符串形式的SimpleDataFormat
2)准备好日期对象Date
3)用SimpleDateFormat的format(Date)函数将日期转换为需要的字符串