今天吃了时间格式化的大亏了,也是不懂js的时间格式化,坑了好长时间。纪念一下,长个记性与大家分享。
java的日期格式化:切记格式为yyyy-MM-dd HH:mm:ss,这个区分大小写。
public static void main(String[] args) {
//正确时间格式
String ddate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
//错误时间格式
String ddate1 = new SimpleDateFormat("yyyy-mm-dd HH:MM:ss").format(new Date());
System.out.println(ddate);
//2015-12-30 14:02:56
System.out.println(ddate1);
//2015-02-30 14:12:56
}
JS的日期格式化:切记js格式为yyyy-mm-dd hh:mm:ss,都是小写。严格区分大小写。
(new Date()).format("yyyy-mm-dd")
"2015-12-30"
(new Date()).format("yyyy-MM-dd")
"2015-51-30"
(new Date(1451444616000)).format("yyyy-mm-dd hh:mm:ss")
"2015-12-30 11:12:36"
(new Date(1451444616000)).format("yyyy-MM-dd hh:MM:ss")
"2015-03-30 11:03:36"
错误出现原因:
由于存数据用的是DateTime类型的,从后台获取数据传到前台时,显示的日期格式给1451444616000,经过yyyy-MM-dd HH:mm:ss格式化后,发现显示时间不对,而并非通过Navicat查询显示的日期数据2015-12-30 11:12:36。由于js时间格式化当时用的跟java一样,显示了错误的时间,导致查不出问题。最后认真检查了一下,才搞明白格式化不统一。
最后注明一下:
java时间格式化:
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())
js时间格式化:
(new Date()).format("yyyy-mm-dd hh:mm:ss")