haizlin/fe-interview

[js] 第49天 写个还剩下多少天过年的倒计时

haizhilin2013 opened this issue · 7 comments

第49天 写个还剩下多少天过年的倒计时

const day =  Math.floor((new Date('2019-12-31 23:59:59:999') - new Date()) / 864e5) // 210

西历新年好算,顺带增加了小时、周、月的维度。农历就懵了……等大佬答案

const countDown = (range = "day") => {
  const nowDate = new Date();
  const currentYear = nowDate.getFullYear();
  const nextYear = new Date(currentYear + 1, 1, 1);

  const rangeBase = {
    minute: 1000 * 60,
    hour: 1000 * 60 * 60,
    day: 1000 * 60 * 60 * 24,
    week: 1000 * 60 * 60 * 24 * 7,
    month: 1000 * 60 * 60 * 24 * 30
  };

  return Math.floor(
    (nextYear.valueOf() - nowDate.valueOf()) /
      (rangeBase[range] || rangeBase.day)
  );
};

console.log(countDown("hour"));
console.log(countDown());
console.log(countDown("week"));
console.log(countDown("month"));

const getLastDays = function () { return Math.floor((new Date('2019-12-31 23:59:59:999') - new Date().getTime())/(24*3600000)); }

Math.floor((new Date("2019-12-31") - Date.now()) / (10**5 *36*24))

西历新年好算,顺带增加了小时、周、月的维度。农历就懵了……等大佬答案

const countDown = (range = "day") => {
  const nowDate = new Date();
  const currentYear = nowDate.getFullYear();
  const nextYear = new Date(currentYear + 1, 1, 1);

  const rangeBase = {
    minute: 1000 * 60,
    hour: 1000 * 60 * 60,
    day: 1000 * 60 * 60 * 24,
    week: 1000 * 60 * 60 * 24 * 7,
    month: 1000 * 60 * 60 * 24 * 30
  };

  return Math.floor(
    (nextYear.valueOf() - nowDate.valueOf()) /
      (rangeBase[range] || rangeBase.day)
  );
};

console.log(countDown("hour"));
console.log(countDown());
console.log(countDown("week"));
console.log(countDown("month"));

我也想知道算阴历的话应该怎么算

西历新年好算,顺带增加了小时、周、月的维度。农历就懵了……等大佬答案

const countDown = (range = "day") => {
  const nowDate = new Date();
  const currentYear = nowDate.getFullYear();
  const nextYear = new Date(currentYear + 1, 1, 1);

  const rangeBase = {
    minute: 1000 * 60,
    hour: 1000 * 60 * 60,
    day: 1000 * 60 * 60 * 24,
    week: 1000 * 60 * 60 * 24 * 7,
    month: 1000 * 60 * 60 * 24 * 30
  };

  return Math.floor(
    (nextYear.valueOf() - nowDate.valueOf()) /
      (rangeBase[range] || rangeBase.day)
  );
};

console.log(countDown("hour"));
console.log(countDown());
console.log(countDown("week"));
console.log(countDown("month"));

抬个杠,new Date()的第二个参数是monthIndex,取值是0-11

console.log(Math.floor((new Date('2022-12-31 23:59:59:999') - new Date()) / 86400000))