分类一:将日期转换为时间戳code
要将日期转换为时间戳,首先得先获取到日期,这里能够直接指定日期,或者是使用当前日期。要获取当前日期,咱们能够使用new Date()来获取:对象
(1)、将当前日期转换为时间戳。get
var now = new Date(); console.log(now.getTime()) // 将当前日期转换为时间戳,getTime()方法可返回距1970年1月1日之间的毫秒数
(2)、将指定日期转换为时间戳。console
var t = "2017-12-08 20:5:30"; // 月、日、时、分、秒若是不满两位数可不带0. var T = new Date(t); // 将指定日期转换为标准日期格式。Fri Dec 08 2017 20:05:30 GMT+0800 (中国标准时间) console.log(T.getTime()) // 将转换后的标准日期转换为时间戳。
分类二:将时间戳转换为日期date
var t = 787986456465; // 当参数为数字的时候,那么这个参数就是时间戳,被视为毫秒,建立一个距离1970年1月一日指定毫秒的时间日期对象。 console.log(new Date(t)) // Wed Dec 21 1994 13:07:36 GMT+0800 (中国标准时间) var t2 = "2017-5-8 12:50:30"; console.log(new Date(t2)) // Mon May 08 2017 12:50:30 GMT+0800 (中国标准时间) var t3 = "2017-10-1"; console.log(new Date(t3)) // Sun Oct 01 2017 00:00:00 GMT+0800 (中国标准时间) 不设定时分秒,则默认转换为00:00:00
通常状况下new Date(time)能够转换以"-","/",等分隔的日期形式,可是在ie中会出现不兼容的问题方法
var date="2017-09-28 10:10:10"; date=date.replace(new RegExp(/-/gm) ,"/");//将全部的'-'转为'/'便可 new Date(date)