获取每隔一定间隔的时间

/**
 *
 * @param {*} n小时
 * @param {*} option{
 *  time:时间
 *  spacing:间隔时间(单位分钟)
 * }
 * @returns 获取从time时间前的n小时前每隔spacing的间隔时间
 */
export function getTimeSpa(n, option) {
  //获取当前时间-24小时
  const t = 1000 * 60; //一分钟的时间戳
  let s = n ? n * 60 * t : 24 * 60 * t; //24就是96个时间
  let d = new Date().getTime();
  let spa = 15 * t;
  if (option) {
    const { time, spacing } = option;
    d = new Date(time).getTime();
    spa = spacing * t;
  }
  var result = [];
  let i = 0;
  while (i < s) {
    result.push(parseTime(d - i));
    i += spa; //计入当前
  }
  return result.reverse();
}

/**
 * 转换时间
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null;
  }
  const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (typeof time === "string") {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time);
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), "/");
      }
    }

    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    return value.toString().padStart(2, "0");
  });
  return time_str;
}

getTimeSpa(1)//一小时前的时间间隔

[
    "2023-08-08 15:26:37",
    "2023-08-08 15:41:37",
    "2023-08-08 15:56:37",
    "2023-08-08 16:11:37"
]

你可能感兴趣的:(vue.js,前端)