JavaScript 日期与时间戳互转(传格式转日期)

 

  1、时间戳转日期格式:

 1   console.log(timestampToTime(new Date().getTime(),'yyyy-mm-dd hh:MM:ss'));
 2   
 3   //时间戳转 日期
 4   function timestampToTime (timestamp,format) {
 5     var date = new Date(timestamp); //时间戳为10位需*1000,时间戳为13位的话不需乘1000
6 7 let config={ 8 yyyy:"", 9 mm:"", 10 dd:"", 11 hh:"", 12 MM:"", 13 ss:"", 14 } 15 16 config.yyyy = date.getFullYear(); 17 config.mm = (date.getMonth()+1 < 10 ? '-'+'0'+(date.getMonth()+1) : '-'+date.getMonth()+1); 18 config.dd = date.getDate()<10?'-'+'0'+date.getDate() + ' ':'-'+date.getDate(); 19 config.hh = ' '+date.getHours(); 20 config.MM = ':'+date.getMinutes(); 21 config.ss = ':'+date.getSeconds(); 22 23 let result=''; 24 for(let item in config){ 25 if(format.indexOf(item)!=-1){ 26 result+=config[item]; 27 } 28 } 29 return result 30 }

 

  2、日期转时间戳:

  

1 var date = new Date('2014-04-23 18:55:49:123');
2     // 有三种方式获取
3     var time1 = date.getTime();
4     var time2 = date.valueOf();
5     var time3 = Date.parse(date);
6     console.log(time1);//1398250549123
7     console.log(time2);//1398250549123
8     console.log(time3);//1398250549000

 

timestamp
posted @ 2018-03-27 11:25  小旺同学  阅读(338)  评论(0编辑  收藏  举报