1 //获取时间戳 单位:秒; 2 3 //1. 获取当前时间戳 4 function getUnixTime(){ 5 var date = new Date(); 6 //使用getTime方法; 7 var unix_time = date.getTime(); 8 9 //使用parse方法; 10 var unix_time = Date.parse(date); 11 12 //使用valueOf()方法; 13 var unix_time = date.valueOf(); 14 15 //js获取的时间戳为毫秒级;转换为秒; 16 return Math.round(unix_time / 1000); 17 } 18 19 //2. 获取指定时间的时间戳 20 //这种的获取时间戳对时间格式有限制; 如2016-04-28 09:04:30或2016/04/28 09:04:30或04-28-2016 09:04:30或者04/28/2016 09:04:30 21 function getUTime(time){ 22 var d = Date.parse(time); 23 return d; 24 } 25 26 //3. 匹配时间字符串中的日期、时间; 27 function getUTime1(time){ 28 var exp = /d+/g; 29 var date = time.match(exp); 30 console.log(date); 31 } 32 getUTime1('01/10/1992 12:12:12'); // 输出["01", "10", "1992", "12", "12", "12"] 33 34 //4. 当分别有年、月、日、时、分、秒时获取时间戳; 35 // 这里所有参数都是非必填; 36 // 这里month需注意:一月是从0开始; 37 var d = new Date(year, month, day, hour, minute, second); 38 console.log(Date.parse(d)); // 获取的时间戳为毫秒;
原文链接:https://blog.icotools.cn/2019/07/23/js-%e8%8e%b7%e5%8f%96%e6%97%b6%e9%97%b4%e6%88%b3/