获取当前时间

/**
 * 获取"年-月-日"
 */
 function getDate() {
  var ddd = new Date();
  var month, day;
  if (ddd.getMonth() < 9) {
    month = "0" + (ddd.getMonth() + 1);
  } else {
    month = (ddd.getMonth() + 1);
  }
  if (ddd.getDate() < 10) {
    day = "0" + ddd.getDate();
  } else {
    day = ddd.getDate();
  }
  var date = ddd.getFullYear() + "-" + month + "-" + day;
  return date;
}

/**
 * 获取"年-月-日 时:分:秒"
 */
function getDatetime(DateTime) {
  var ddd;
  if(DateTime){
    ddd = DateTime;
  }else{
    ddd = new Date();
  }
  var month, day, hours, minutes,seconds;
  if (ddd.getMonth() < 9) {
    month = "0" + (ddd.getMonth() + 1);
  } else {
    month = (ddd.getMonth() + 1);
  }
  if (ddd.getDate() < 10) {
    day = "0" + ddd.getDate();
  } else {
    day = ddd.getDate();
  }
  if (ddd.getHours() < 10) {
    hours = "0" + ddd.getHours();
  } else {
    hours = ddd.getHours();
  }
  if (ddd.getMinutes() < 10) {
    minutes = "0" + ddd.getMinutes();
  } else {
    minutes = ddd.getMinutes();
  } 
  if (ddd.getSeconds() < 10) {
    seconds = "0" + ddd.getSeconds();
  } else {
    seconds = ddd.getSeconds();
  }
  var datew = ddd.getFullYear() + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
  return datew;
}

/**
 * 获取"时:分:秒"
 */
function hms() {
  var ddd = new Date();
  var hours, minutes, seconds;
  if (ddd.getHours() < 10) {
    hours = "0" + ddd.getHours();
  } else {
    hours = ddd.getHours();
  }
  if (ddd.getMinutes() < 10) {
    minutes = "0" + ddd.getMinutes();
  } else {
    minutes = ddd.getMinutes();
  }
  if (ddd.getSeconds() < 10) {
    seconds = "0" + ddd.getSeconds();
  } else {
    seconds = ddd.getSeconds();
  }
  var datew = hours + ":" + minutes+ ":" + seconds;
  return datew;
}

/** 
  *获取"星期几"
  */
function getWeekDay(date) {
  var date = new Date();
  let weekDay = date.getDay(); 
  //获取当前星期X(0-6,0代表星期天)
  switch(weekDay) {
      case 0:
          weekDay = "星期日";
          break;
      case 1:
          weekDay = "星期一";
          break;
      case 2:
          weekDay = "星期二";
          break;
      case 3:
          weekDay = "星期三";
          break;
      case 4:
          weekDay = "星期四";
          break;
      case 5:
          weekDay = "星期五";
          break;
      case 6:
          weekDay = "星期六";
          break;
      default:break;
  }
  return weekDay;
}
module.exports = {
  getDate,
  getDatetime,
  hms,
  getWeekDay,
}

你可能感兴趣的:(js)