美文网首页
JS 获取 近**天,前天,昨天,今天,明天,后天,未来**天等

JS 获取 近**天,前天,昨天,今天,明天,后天,未来**天等

作者: Cherry丶小丸子 | 来源:发表于2021-06-20 16:16 被阅读0次
/**
 * 获取 近**天,前天,昨天,今天,明天,后天,未来**天等通用方法
 * ..............and so on
 * -15 ----- 近15天
 *  -7 ----- 近7天
 *  -3 ----- 近3天
 *  -2 ----- 前天
 *  -1 ----- 昨天
 *   0 ------------------------- 今天
 *   1 ----- 明天
 *   2 ----- 后天
 *   3 ----- 未来3天
 *   7 ----- 未来7天
 *  15 ----- 未来15天
 * ..............and so on
 * @param {Object} count
 */
timeFormat(count) {
    // 实例化开始日期
    const startDate = new Date();
    // 以毫秒设置 Date 对象
    if(count > 2){
        startDate.setTime(startDate.getTime()); // 大于2,设置起始时间为今天
    }else if(count < -2){
        startDate.setTime(startDate.getTime() + (24 * 60 * 60 * 1000) * (count + 1));
    }else{
        startDate.setTime(startDate.getTime() + (24 * 60 * 60 * 1000) * count);
    }
    // 获取开始年份
    const startY = startDate.getFullYear();
    // 获取开始月份
    const startM = startDate.getMonth() + 1 < 10 ? '0' + (startDate.getMonth() + 1) : startDate.getMonth() + 1;
    // 获取开始日
    const startD = startDate.getDate() < 10 ? '0' + startDate.getDate() : startDate.getDate();
    // 拼接 最终开始时间
    const startTime = `${startY}-${startM}-${startD} 00:00:00`;
    
    
    
    // 实例化结束日期
    const endDate = new Date();
    // 以毫秒设置 Date 对象
    if(count > 2){
        endDate.setTime(endDate.getTime() + (24 * 60 * 60 * 1000) * (count - 1));
    }else if(count < -2){
        endDate.setTime(endDate.getTime()); // 小于-2,设置结束时间为今天
    }else{
        endDate.setTime(endDate.getTime() + (24 * 60 * 60 * 1000) * count);
    }
    // 获取结束年份
    const endY = endDate.getFullYear();
    // 获取结束月份
    const endM = endDate.getMonth() + 1 < 10 ? '0' + (endDate.getMonth() + 1) : endDate.getMonth() + 1;
    // 获取结束日
    const endD = endDate.getDate() < 10 ? '0' + endDate.getDate() : endDate.getDate();
    // 拼接 最终结束时间
    const endTime = `${endY}-${endM}-${endD} 23:59:59`;
    
    // 返回 开始 至 结束 日期 数组
    return [startTime, endTime];
}

相关文章

网友评论

      本文标题:JS 获取 近**天,前天,昨天,今天,明天,后天,未来**天等

      本文链接:https://www.haomeiwen.com/subject/cdrsyltx.html