JS 时间格式转换

this.timeFormatConvert(new Date()) // 2022-11-26 21:37:29

/** 时间格式转换
 * @param e 要转换的日期(如:Sat Nov 26 2022 21:37:29 GMT+0800 (中国标准时间))
 * @returns {string} 转换结果(如:2022-11-26 21:37:29)
 */
timeFormatConvert(e) {
  const Y = e.getFullYear(); // 年
  const M = this.prefixZero(e.getMonth() + 1); // 月
  const D = this.prefixZero(e.getDate()); // 日
  const H = this.prefixZero(e.getHours()); // 时
  const Mi = this.prefixZero(e.getMinutes()); // 分
  const S = this.prefixZero(e.getSeconds()); // 秒
  return Y + "-" + M + "-" + D + " " + H + ":" + Mi + ":" + S;
},
prefixZero(num = 0, n = 2) {
  // 数字位数不够,数字前面补零
  return (Array(n).join("0") + num).slice(-n);
},

JS 获取当前年月日时分秒

this.getCurrTime("noGap") // 20221129154229

this.getCurrTime() // 2022-11-29 15:44:20

/** 获取当前年月日时分秒
 * @param e 默认.年月日时分秒 date.年月日 dateTime.年月日时分 noGap.无分隔符的年月日时分秒
 * @returns {string}
 */
getCurrTime(e = "") {
  const curDate = new Date(),
    T = {
      Y: curDate.getFullYear().toString(), // 年
      M: this.prefixZero(curDate.getMonth() + 1), // 月
      D: this.prefixZero(curDate.getDate()), // 日
      H: this.prefixZero(curDate.getHours()), // 时
      Mi: this.prefixZero(curDate.getMinutes()), // 分
      S: this.prefixZero(curDate.getSeconds()), // 秒
    },
    tDate = T.Y + "-" + T.M + "-" + T.D; // 年月日
  let result = tDate + " " + T.H + ":" + T.Mi + ":" + T.S; // 年月日时分秒
  if (e === "date") result = tDate; // 年月日
  if (e === "dateTime") result = tDate + " " + T.H + ":" + T.Mi; // 年月日时分
  if (e === "noGap") result = T.Y + T.M + T.D + T.H + T.Mi + T.S; // 无分隔符
  return result;
},
prefixZero(num = 0, n = 2) {
  // 数字位数不够,数字前面补零
  return (Array(n).join("0") + num).slice(-n);
},

JS 获取n天前或n天后的日期

当前日期:2022-11-27

7天后的日期:this.getAgoLaterDate(7) // 2022-12-04

7天前的日期:this.getAgoLaterDate(-7) // 2022-11-20

/** 获取n天前或n天后的日期(默认当天)
 * @param n 需要的天数(+n之后的日期,-n之前的日期)
 * @returns {string} 默认返回当前日期
 */
getAgoLaterDate(n = 0) {
  const curTime = new Date(),
    D1 = curTime.getDate(),
    date = new Date(curTime);
  date.setDate(D1 + n);
  const Y2 = date.getFullYear(),
    M2 = this.prefixZero(date.getMonth() + 1),
    D2 = this.prefixZero(date.getDate());
  return Y2 + "-" + M2 + "-" + D2;
},
prefixZero(num = 0, n = 2) {
  // 数字位数不够,数字前面补零
  return (Array(n).join("0") + num).slice(-n);
},

JS 获取指定日期的周一和周日

this.getSpecifyMonSun() // {mon: '2022-11-21', sun: '2022-11-27'}

this.getSpecifyMonSun("2022/11/17") // {mon: '2022-11-14', sun: '2022-11-20'}

/** 获取指定日期的周一和周日(默认当前日期)
 * @param e 需要指定的日期(格式:yyyy-MM-dd 或 yyyy/MM/dd 或 yyyy.MM.dd)
 * @returns {{mon: string, sun: string}} 默认返回当前日期的周一和周末日期
 */
getSpecifyMonSun(e = new Date()) {
  const that = this,
    now = new Date(e),
    nowTime = now.getTime(),
    day = now.getDay() || 7, // 周日时day修改为7,否则获取的是下周一到周日的日期
    oneDayTime = 24 * 60 * 60 * 1000, // 一天的毫秒(ms)数
    mondayTime = new Date(nowTime - (day - 1) * oneDayTime), //周一的日期
    sundayTime = new Date(nowTime + (7 - day) * oneDayTime); //周日的日期
  function dataFormat(d) {
    const Y = d.getFullYear(), // 年
      M = that.prefixZero(d.getMonth() + 1), // 月
      D = that.prefixZero(d.getDate()); // 日
    return Y + "-" + M + "-" + D;
  }
  return { mon: dataFormat(mondayTime), sun: dataFormat(sundayTime) };
},
prefixZero(num = 0, n = 2) {
  // 数字位数不够,数字前面补零
  return (Array(n).join("0") + num).slice(-n);
},

JS 获取指定日期的周一至周日的所有日期

this.getSpecifyWeekAllTime() // ['2023-01-30', '2023-01-31', '2023-02-01', '2023-02-02', '2023-02-03', '2023-02-04', '2023-02-05']

this.getSpecifyWeekAllTime('2023-01-19') // ['2023-01-16', '2023-01-17', '2023-01-18', '2023-01-19', '2023-01-20', '2023-01-21', '2023-01-22']

/** 获取指定日期的周一至周日的所有日期
 * @param e 需要指定的日期(格式:yyyy-MM-dd 或 yyyy/MM/dd 或 yyyy.MM.dd)
 * @param t date.只返回月与日(默认返回年月日)
 * @returns {*[]} 默认返回当前日期的周一至周日的所有日期
 */
getSpecifyWeekAllTime(e = new Date(), t = '') {
  const timeStamp = new Date(e).getTime(),
    curDay = new Date(e).getDay(),
    dateList = [];
  for (let i = 0; i < 7; i++) {
    const das = new Date(timeStamp + 24 * 60 * 60 * 1000 * (i - ((curDay + 6) % 7)));
    const Y = das.getFullYear(), // 年
      M = this.prefixZero(das.getMonth() + 1), // 月
      D = this.prefixZero(das.getDate()); // 日
    let val = Y + '-' + M + '-' + D;
    if (t === 'date') val = M + '-' + D;
    dateList.push(val);
  }
  return dateList;
},
prefixZero(num = 0, n = 2) {
  // 数字位数不够,数字前面补零
  return (Array(n).join('0') + num).slice(-n);
},

JS 获取指定日期的月初和月末

this.getSpecifyEarlyEndMonth() // {first: '2022-11-01', end: '2022-11-30'}

this.getSpecifyEarlyEndMonth("2022/09") // {first: '2022-09-01', end: '2022-09-30'}

/** 获取指定日期的月初和月末(默认当前月)
 * @param e 需要指定的日期(格式:yyyy-MM 或 yyyy/MM 或 yyyy.MM)
 * @returns {{end: string, first: string}} 默认返回当前月的月初和月末日期
 */
getSpecifyEarlyEndMonth(e = new Date()) {
  const that = this,
    nowDate = new Date(e), // 当前日期
    year = nowDate.getFullYear(), // 指定年
    month = nowDate.getMonth() + 1, // 指定月
    oneDayTime = 24 * 60 * 60 * 1000, // 一天的毫秒(ms)数
    firstDay = new Date(year, month - 1), // 当月第一天的日期
    lastDay = new Date(new Date(year, month).valueOf() - oneDayTime); // 当月最后一天的日期
  function dataFormat(d) {
    const Y = d.getFullYear(), // 年
      M = that.prefixZero(d.getMonth() + 1), // 月
      D = that.prefixZero(d.getDate()); // 日
    return Y + "-" + M + "-" + D;
  }
  return { first: dataFormat(firstDay), end: dataFormat(lastDay) };
},
prefixZero(num = 0, n = 2) {
  // 数字位数不够,数字前面补零
  return (Array(n).join("0") + num).slice(-n);
},

JS 获取指定年份季度的开始和结束日期

this.getSpecifyQuarter(); // { "first": "2023-01-01", "end": "2023-03-31" }

/** 获取指定年份季度的开始和结束日期(默认今年的第一季度)
 * @param year 指定的年份
 * @param qtr 指定的季度
 * @returns {{end: string, first: string}} 默认返回今年第一季度的日期
 */
getSpecifyQuarter(year = new Date().getFullYear(), qtr = 1) {
  let val = 0; // 第一季度
  if (qtr === 2) {
    val = 3; // 第二季度
  } else if (qtr === 3) {
    val = 6; // 第三季度
  } else if (qtr === 4) {
    val = 9; // 第四季度
  }
  const startDate = new Date(year, val, 1);
  const endDate = new Date(year, val + 2, getMonthDays(year, val + 2));
  // 日期格式化
  function dataFormat(d) {
    const Y = d.getFullYear(), // 年
      M = prefixZero(d.getMonth() + 1), // 月
      D = prefixZero(d.getDate()); // 日
    return Y + "-" + M + "-" + D;
  }
  // 数字位数不够,数字前面补零
  function prefixZero(num = 0, n = 2) {
    return (Array(n).join("0") + num).slice(-n);
  }
  // 获得指定月份的天数
  function getMonthDays(y, m) {
    const monthStart = new Date(y, m, 1);
    const monthEnd = new Date(y, m + 1, 1);
    return (monthEnd - monthStart) / (1000 * 60 * 60 * 24);
  }
  return { first: dataFormat(startDate), end: dataFormat(endDate) };
},

JS 根据当前时间判断是早上、中午、下午

this.getCurTimeState() // 晚上好

/** 根据当前时间判断是早上、中午、下午
 * @returns {string} 返回当前时间段对应的状态
 */
getCurTimeState() {
  const nowTime = new Date(), // 获取当前时间
    hour = nowTime.getHours(); // 获取当前小时
  let result = ""; // 设置默认文字
  // 判断当前时间段
  if (hour >= 0 && hour <= 10) {
    result = "早上好";
  } else if (hour > 10 && hour <= 14) {
    result = "中午好";
  } else if (hour > 14 && hour <= 18) {
    result = "下午好";
  } else if (hour > 18 && hour <= 24) {
    result = "晚上好";
  }
  return result; // 返回当前时间段对应的状态
},

JS 将年月日时分秒转化为刚刚,几分钟前,几小时前,几天前等

this.timeConvertReveal("2020-11-27 14:38:16") // 2年前

this.timeConvertReveal() // 刚刚

/** 将年月日时分秒转化为刚刚,几分钟前,几小时前,几天前等(默认刚刚)
 * @param e 需要转换的时间(格式:yyyy-MM-dd HH:mm:ss 或 yyyy/MM/dd HH:mm:ss 或 yyyy.MM.dd HH:mm:ss)
 * @returns {string} 默认返回刚刚
 */
timeConvertReveal(e = new Date()) {
  const minute = 1000 * 60, // 分钟
    hour = minute * 60, // 小时
    day = hour * 24, // 天
    week = day * 7, // 周
    month = day * 30, // 月
    year = month * 12, // 年
    curTime = new Date().getTime(), // 当前时间的时间戳
    specifyTime = new Date(e), // 指定时间的时间戳
    mistiming = curTime - specifyTime, // 时间差
    yearDiffer = mistiming / year, // 年差
    monthDiffer = mistiming / month, // 月差
    weekDiffer = mistiming / week, // 周差
    dayDiffer = mistiming / day, // 天差
    hourDiffer = mistiming / hour, // 时差
    minuteDiffer = mistiming / minute; // 分钟差
  let result = "-";
  if (yearDiffer >= 1) result = toInt(yearDiffer) + "年前";
  else if (monthDiffer >= 1) result = toInt(monthDiffer) + "月前";
  else if (weekDiffer >= 1) result = toInt(weekDiffer) + "周前";
  else if (dayDiffer >= 1) result = toInt(dayDiffer) + "天前";
  else if (hourDiffer >= 1) result = toInt(hourDiffer) + "小时前";
  else if (minuteDiffer >= 1) result = toInt(minuteDiffer) + "分钟前";
  else result = "刚刚";
  function toInt(num) {
    return parseInt(num.toString());
  }
  return result;
},

JS 获得指定月份的天数

this.getMonthDays("2022-10") // 31

/** 获得指定月份的天数(默认当前月)
 * @param e 需要指定的日期(格式:yyyy-MM 或 yyyy/MM 或 yyyy.MM)
 * @returns {number} 默认返回当前月的天数
 */
getMonthDays(e = new Date()) {
  const now = new Date(e), // 指定日期
    nowYear = now.getYear(), // 指定年份
    nowMonth = now.getMonth(), // 指定月份
    startDate = new Date(nowYear, nowMonth, 1), // 开始日期
    endDate = new Date(nowYear, nowMonth + 1, 1); // 结束日期
  return (endDate - startDate) / (1000 * 60 * 60 * 24);
},

JS 获取指定日期是周几

this.getCurrWeek("2022-11-24") // 周四

this.getCurrWeek() // 周二

/** 获取指定日期是周几
 * @param e 需要指定的日期(格式:yyyy-MM-dd 或 yyyy/MM/dd 或 yyyy.MM.dd)
 * @returns {string} 默认返回当前日期是周几
 */
getCurrWeek(e = new Date()) {
  const day = new Date(e).getDay(),
    weeks = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
  return weeks[day];
},

JS 计算两个时间的时间差

this.getTimeDiff("2022-11-28 19:30:24") // {text: '时间已超过30分钟', timeDiff: '0天21时28分40秒40毫秒', dateObj: {day: 0, hour: 21, min: 28, sec: 40, ms: 40}}

/** 计算两个时间的时间差(timeDiff返回格式为xx天xx时xx分xx秒xx毫秒)
 * @param startTime 开始时间(格式:yyyy-MM-dd HH:mm:ss 或 yyyy/MM/dd HH:mm:ss 或 yyyy.MM.dd HH:mm:ss [需小于结束时间])
 * @param endTime 结束时间(格式:yyyy-MM-dd HH:mm:ss 或 yyyy/MM/dd HH:mm:ss 或 yyyy.MM.dd HH:mm:ss [默认当前时间])
 * @returns {string|{timeDiff: string, text: string, dateObj: {sec: number, min: number, hour: number, ms: number, day: number}}}
 */
getTimeDiff(startTime, endTime = new Date()) {
  if (!startTime) return "错误:开始时间为必填";
  const diffVal = new Date(endTime) - new Date(startTime); // 两个时间戳相差的毫秒数
  if (diffVal < 0) return "错误:开始时间大于结束时间";
  const day = Math.floor(diffVal / (24 * 3600 * 1000)), // 计算相差的天数
    remainDay = diffVal % (24 * 3600 * 1000), // 计算天数后剩余的毫秒数
    hour = Math.floor(remainDay / (3600 * 1000)), // 计算相差的小时数
    remainHour = remainDay % (3600 * 1000), // 计算小时数后剩余的毫秒数
    min = Math.floor(remainHour / (60 * 1000)), // 计算相差的分钟数
    remainMinute = remainHour % (60 * 1000), // 计算分钟数后剩余的毫秒数
    sec = Math.round(remainMinute / 1000), // 计算相差的秒数
    remainSeconds = remainMinute % (60 * 1000), // 计算秒数后剩余的毫秒数
    ms = Math.round(remainSeconds / 1000), // 计算相差的毫秒数
    time = day + "天" + hour + "时" + min + "分" + sec + "秒" + ms + "毫秒",
    obj = { day: day, hour: hour, min: min, sec: sec, ms: ms };
  let val = "时间未超过30分钟";
  if (min > 30 || hour > 1) val = "时间已超过30分钟";
  return { text: val, timeDiff: time, dateObj: obj };
},

JS 从日期字符串中截取出年、月、日、时、分、秒

this.captureTime() // {day: "29", hour: "17", minute: "40", month: "11", second: "06", year: "2022"}

this.captureTime("2020-12-11 14:54:48") // {day: "11", hour: "14", minute: "54", month: "12", second: "48", year: "2020"}

/** 从日期字符串中截取出年、月、日、时、分、秒
 * @param e 需要截取的日期(格式:yyyy-MM-dd HH:mm:ss 或 yyyy/MM/dd HH:mm:ss 或 yyyy.MM.dd HH:mm:ss [默认当前日期])
 * @returns {{month: *, hour: *, year: *, day: *, minute: *, second: *}} 默认返回当前日期
 */
captureTime(e = null) {
  let time = e;
  if (!e) {
    const curDate = new Date(),
      T = {
        Y: curDate.getFullYear().toString(), // 年
        M: this.prefixZero(curDate.getMonth() + 1), // 月
        D: this.prefixZero(curDate.getDate()), // 日
        H: this.prefixZero(curDate.getHours()), // 时
        Mi: this.prefixZero(curDate.getMinutes()), // 分
        S: this.prefixZero(curDate.getSeconds()), // 秒
      };
    time = T.Y + "-" + T.M + "-" + T.D + " " + T.H + ":" + T.Mi + ":" + T.S;
  }
  const timeArr = time.replace(/[:. /]/g, "-").split("-"); // 将":. /"换为"-",再根据"-"分组
  return {
    year: timeArr[0], // 年
    month: timeArr[1], // 月
    day: timeArr[2], // 日
    hour: timeArr[3], // 时
    minute: timeArr[4], // 分
    second: timeArr[5], // 秒
  };
},
prefixZero(num = 0, n = 2) {
  // 数字位数不够,数字前面补零
  return (Array(n).join("0") + num).slice(-n);
},
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。