美文网首页
常见的日期处理工具

常见的日期处理工具

作者: 扶得一人醉如苏沐晨 | 来源:发表于2022-08-02 11:54 被阅读0次

// 获取当前时间 YYYY-MM-DD HH-MM-SS

function getNowTime() {

  const yy = new Date().getFullYear();

  const MM =

    new Date().getMonth() + 1 < 10

      ? "0" + (new Date().getMonth() + 1)

      : new Date().getMonth() + 1;

  const dd =

    new Date().getDate() < 10

      ? "0" + new Date().getDate()

      : new Date().getDate();

  const HH =

    new Date().getHours() < 10

      ? "0" + new Date().getHours()

      : new Date().getHours();

  const mm =

    new Date().getMinutes() < 10

      ? "0" + new Date().getMinutes()

      : new Date().getMinutes();

  const ss =

    new Date().getSeconds() < 10

      ? "0" + new Date().getSeconds()

      : new Date().getSeconds();

  return yy + "-" + MM + "-" + dd + " " + HH + ":" + mm + ":" + ss;

}

// 根据开始时间和期限计算结束时间

function getNewDay(dateTemp, days) {

  dateTemp = dateTemp.split("-");

  //转换为MM-DD-YYYY格式

  var nDate = new Date(dateTemp[1] + "-" + dateTemp[2] + "-" + dateTemp[0]);

  var millSeconds = Math.abs(nDate) + days * 24 * 60 * 60 * 1000;

  var rDate = new Date(millSeconds);

  var year = rDate.getFullYear();

  var month = rDate.getMonth() + 1;

  if (month < 10) month = "0" + month;

  var date = rDate.getDate();

  if (date < 10) date = "0" + date;

  return year + "-" + month + "-" + date;

}

// 获取当前年月日 YYYY-MM-DD

也可以直接 利用dayjs插件 this.dayjs("new Date").format("YYYY-MM-DD")

function getNowFormatDate() {

  let date = new Date(),

    seperator1 = "-", //格式分隔符

    year = date.getFullYear(), //获取完整的年份(4位)

    month = date.getMonth() + 1, //获取当前月份(0-11,0代表1月)

    strDate = date.getDate(); // 获取当前日(1-31)

  if (month >= 1 && month <= 9) month = "0" + month; // 如果月份是个位数,在前面补0

  if (strDate >= 0 && strDate <= 9) strDate = "0" + strDate; // 如果日是个位数,在前面补0

  let currentdate = year + seperator1 + month + seperator1 + strDate;

  return currentdate;

}

//比较日期大小年月日 YYYY-MM-DD

function compareDate(currentTime, endTime) {

  var currentTimes = currentTime.split("-");

  var endTimes = endTime.split("-");

  var currentTimesTmp =

    currentTimes[0] + "/" + currentTimes[1] + "/" + currentTimes[2];

  var endTimesTmp = endTimes[0] + "/" + endTimes[1] + "/" + endTimes[2];

  if (

    Date.parse(new Date(currentTimesTmp)) >= Date.parse(new Date(endTimesTmp))

  ) {

    return true;

  } else {

    return false;

  }

}

export default { getNowTime, getNewDay, getNowFormatDate, compareDate };

相关文章

网友评论

      本文标题:常见的日期处理工具

      本文链接:https://www.haomeiwen.com/subject/kgzdwrtx.html