js——时间戳转换、日期格式转换

  1. 获得当前日期
let date = new Date()
console.log(date);
console.log(typeof date); // obj
console.log(date * 1); // 时间戳

let date1 = Date()
console.log(date1);
console.log(typeof date1); //string
console.log(date1 * 1); //NaN

 

  2.  日期转换成时间戳

let date5 = new Date()
console.log(date5 * 1);
console.log(Number(date5));
console.log(date5.valueOf());
console.log(date5.getTime());

 

  3. 封装日期格式化函数

let date6 = new Date()
function dateFormatFn(date,format='YYYY-MM-DD HH:mm:ss'){
  let config = {
    YYYY:date.getFullYear(),
    MM:date.getMonth()+1 >10?date.getMonth()+1:'0'+(date.getMonth()+1),
    DD:date.getDate(),
    HH:date.getHours()>10?date.getHours():'0'+(date.getHours()),
    mm:date.getMinutes(),
    ss:date.getSeconds()
  }
  for(const key in config){
    format = format.replace(key,config[key])
  }
  return format
}
console.log(dateFormatFn(date6));

执行结果为:

 

  4. 使用moment.js格式化日期

<script src="https://cdn.bootcdn.net/ajax/libs/moment.js/1.1.1/moment.js"></script>
<script>
  console.log(moment().format('YYYY-MM-DD HH:mm:ss'));
</script>

 

 

8篇。

 

posted @ 2020-09-29 09:55  小昱同学  阅读(2800)  评论(0编辑  收藏  举报