JS 获取 近**天,前天,昨天,今天,明天,后天,未来**天等通用方法

/**
 * 获取 近 ** 天,前天,昨天,今天,明天,后天,未来 ** 天等通用方法
 * ..............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];
}

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容