js中创建format函数,格式化当前时间

//在形参中设置具体的时间格式

function format(str){
  var now = new Date();
  var year = now.getFullYear();
  var month = now.getMonth()+1;
  var date = now.getDate();
  //根据参数所传递的时间格式来进行具体的操作
  if(str == 'yyyy-mm-dd'){
    return year + '-' + month + '-' + date;
  }else if(str == 'mm/dd/yyyy'){
    return month + '/' + date + '/' + year;
  }
}
var res1 = format('yyyy-mm-dd');
console.log(res1);
var res2 = format('mm/dd/yyyy');
console.log(res2);

你可能感兴趣的:(js中创建format函数,格式化当前时间)