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篇。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM