获取相对时间周期(日、周、月),不涉及第三方库

738 阅读1分钟

方法

  • 转换时间格式拼接
  // 转换时间格式
  function formatDate(date, seperator = '-') {
    var oYear = date.getFullYear();
    var oMoth = (date.getMonth() + 1).toString();
    if (oMoth.length <= 1) oMoth = '0' + oMoth;
    var oDay = date.getDate().toString();
    if (oDay.length <= 1) oDay = '0' + oDay;
    return oYear + seperator + oMoth + seperator + oDay;
  }
  • 获取日榜
  // 获取相对日期, num: -1 昨天,0 今天, 1明天以此类推
  function getDay(num) {
    var date = new Date();
    var nowTime = date.getTime();
    var ms = 24 * 3600 * 1000 * num;
    date.setTime(parseInt(nowTime + ms));
    return formatDate(date)
  }
  • 获取周榜
  // 获得date的所在周起始时间
  function getWeekDate(baseDate) {
    // 日期格式转换
    var date = new Date(baseDate);
    // 本周一的日期
    date.setDate(date.getDate() - date.getDay() + 1);
    var begin = formatDate(date);
    // 本周日的日期
    date.setDate(date.getDate() + 6);
    var end = formatDate(date);
    return { begin, end }
  }
  • 获取月榜
  // 获取月份周期时间,month -1上个月 0 当前月 1 下个月 默认是上个月
  function getMonthDate(month = -1) {
    var lastMonthDate = new Date();
    var nowYear = lastMonthDate.getFullYear();
    // 获取上个月起始时间
    var nowMonth = lastMonthDate.getMonth() + month;
    var begin = new Date(nowYear, nowMonth, 1);
    // 
    var end = new Date(nowYear, nowMonth, getMonthDays(begin));
    return { begin: formatDate(begin), end: formatDate(end) }
  }
  
  // 获取date所在月份总天数, 默认时间是当天,获取当月天数
  function getMonthDays(baseDate = new Date()){
    var date = new Date(baseDate);
    //将当前月份加月份表示0-11代表1-12月故月份要+1
    date.setMonth(date.getMonth() + 1);
    // 将当前的日期置为0,
    date.setDate(0);
    // 再获取天数即取上个月的最后一天的天数
    return date.getDate();
  }

调用

// 昨天
var yesterday = getDay(-1);
// 上周 倒推七天即是上周
var lastWeek = getWeekDate(getDay(-7));
// 上个月
var lastMonth = getMonthDate(-1);
console.log('day', yesterday, lastWeek, lastMonth)