js时间戳和日期互转换

时间:2022-12-21 02:19:31

1.日期转时间戳

1 //获取当前时间戳
2 new Date().getTime();
3 //获取固定时间的时间戳
4 new Date('2018-12-01 12:22').getTime()

2.时间戳转日期

 

 1 function formatDateTime(timeStamp) { 
 2     var date = new Date();
 3     date.setTime(timeStamp * 1000);
 4     var y = date.getFullYear();    
 5     var m = date.getMonth() + 1;    
 6     m = m < 10 ? ('0' + m) : m;    
 7     var d = date.getDate();    
 8     d = d < 10 ? ('0' + d) : d;    
 9     var h = date.getHours();  
10     h = h < 10 ? ('0' + h) : h;  
11     var minute = date.getMinutes();  
12     var second = date.getSeconds();  
13     minute = minute < 10 ? ('0' + minute) : minute;    
14     second = second < 10 ? ('0' + second) : second;   
15     return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;    
16 };  
17 console.log(formatDateTime(1495157126));