将日期格式转换成时间戳

247 阅读1分钟

参考

js时间戳与日期格式之间的互转 - SegmentFault 思否
How to Convert a Date String to Timestamp in JavaScript? - The Web Dev
xkr.us / javascript…
javascript - Convert normal date to unix timestamp - Stack Overflow
JavaScript专题之跟着 underscore 学节流 · Issue #26 · mqyqingfeng/Blog (github.com)

日期格式转换成时间戳

var time = '2022-04-23 18:55:49:123';
var date = new Date(time);
// var date = new Date(time.replace(/-/g, '/'));

// 有五种种方式获取,在后面会讲到五种方式的区别
console.log(date.getTime());
console.log(date.valueOf());
console.log(+date);
console.log(Date.parse(date));
moment(date).unix();
/* 
五种获取的区别:
前三种:会精确到毫秒
第四种:只能精确到秒,毫秒将用0来代替
第五种:只精确到秒,没有毫秒
比如上面代码输出的结果(一眼就能看出区别):
1650711349123
1650711349123
1650711349123
1650711349000
1650711349
*/

前面四种精确到秒的通用方法

const toTimestamp = (strDate) => {  
  const dt = Date.parse(strDate); 
  //const dt = strDate.getTime(strDate); 
  //const dt = strDate.valueOf(strDate); 
  //const dt = +strDate; 
  return (dt / 1000)>>0;  
}  

最后一种精确到秒的方法 使用moment.js

const toTimestamp = (strDate) => {  
  const dt = moment(strDate).unix();  //unix精确到秒
  return dt;  
}