javascript内置对象Date的使用

Table of Contents

格式化输出yyyy-mm-dd HH:MM:SS.msmsms

function padbyZero(){ // 用零填充
  var val = arguments[0]|0;
  var len = arguments[1]|2;
  var res = null;
  for(var i=1;i<len;i++){
    res = val<Math.pow(10, i)?'0'+val:''+val;
  }
  return res;
}
var d=new Date();
//获取年,getFullYear()返回4位的数字
var year=d.getFullYear();
//获取月,月份比较特殊,从0开始计数
var month=padbyZero(d.getMonth()+1);
//获取日
var day=padbyZero(d.getDate());
var hour=padbyZero(d.getHours());
var minute=padbyZero(d.getMinutes());
var second=padbyZero(d.getSeconds());
var millisceond=padbyZero(d.getMilliseconds(), 3);
formatStr = year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second+'.'+millisceond;
console.log(formatStr);