
function fill0(n) {
  return n > 9 ? `${n}` : `0${n}`
}

export function getParts(dt, pure = false) {
  const y = dt.getFullYear();
  const m = dt.getMonth() + 1;
  const d = dt.getDate();

  return pure ? [y, m, d]
    : [
      y,
      fill0(m),
      fill0(d),
    ]
}

export function getDateStr(dt) {
  const [y, m, d] = getParts(dt);
  return [y, m, d].join('-');
}

export function getMonthStr(dt) {
  const [y, m] = getParts(dt);
  return [y, m].join('-');
}

export function getDtStr(dtStr) {
  return !dtStr ? '' : dtStr.replace('T', ' ').substring(0, 16);
}

// 获取两个日期的天数间隔
export function getDaysBetween(dt1, dt2) {
  const dur = 1000 * 60 * 60 * 24;
  const d1 = getParts(dt1);
  const d2 = getParts(dt2);

  return Math.floor((new Date(d1[0], d1[1] - 1, d1[2]).getTime() - new Date(d2[0], d2[1] - 1, d2[2]).getTime()) / dur);
}

// 获取当前周
export function getCurrentWeek() {
  const now = new Date();
  const year = now.getFullYear();
  const month = now.getMonth();
  const days = now.getDay();
  const today = now.getDate();

  return [
    new Date(year, month, today - days + 1),
    new Date(year, month, today + 7 - days),
  ]
}

// 获取当前月
export function getCurrentMonth() {
  const now = new Date();
  const year = now.getFullYear();
  const month = now.getMonth();

  return [
    new Date(year, month, 1),
    new Date(year, month + 1, 0),
  ]
}

// 获取本年
export function getCurrentYear() {
  const now = new Date();
  const year = now.getFullYear();

  return [
    new Date(year, 0, 1),
    new Date(year, 11, 31),
  ]
}
