js获取上周本周下周的日期(附Demo)

前言

现在的时间点是:2024-04-08,对应的日期如下(上周、这周、下周)

在这里插入图片描述

1. 基本知识

讲述Demo之前,先补充一些基础知识

JavaScript 中的 Date 对象是用于处理日期和时间的对象。它可以获取当前日期和时间,以及可以对日期和时间进行操作

以下是一些基本的 Date 对象的方法和属性:

var now = new Date(); // 创建一个表示当前时间的 Date 对象
var time = now.getTime(); // 获取当前时间的毫秒数,从 1970 年 1 月 1 日开始计算
var year = now.getFullYear(); // 获取当前年份
var date = now.getDate(); // 获取当前日期
var hour = now.getHours(); // 获取当前小时
var second = now.getSeconds(); // 获取当前秒钟
var week = now.getDay(); // 获取当前星期(注意:返回的是 0 表示星期天,1 表示星期一,以此类推)

其余方法如下:

  • getMilliseconds(): 获取当前毫秒数
  • getUTCFullYear():获取 UTC 时间的年份
  • getUTCMonth():获取 UTC 时间的月份
  • getUTCDate():获取 UTC 时间的日期
  • getUTCHours():获取 UTC 时间的小时
  • getUTCMinutes(): 获取 UTC 时间的分钟
  • getUTCSeconds():获取 UTC 时间的秒钟

注意事项:

  • getMonth() 方法返回的月份是从 0 开始的,所以在实际使用时需要加 1
  • getDay() 返回的是星期几的数字表示,需要使用数组或 switch 语句进行转换

JavaScript 的 Date 对象还提供了一系列设置日期和时间的方法,以及进行日期和时间运算的方法,如 setFullYear()setMonth()setDate()setHours() 等,以及 getTimezoneOffset()toUTCString() 等方法用于处理时区和格式化日期等

2. Demo

  1. 使用 moment.js 库来处理日期操作。
  2. 使用 isoWeekday 获取当前日期是一周的第几天,以确定是在本周还是上周或下周。
  3. 使用 startOf('isoWeek')endOf('isoWeek') 来获取本周的起始日期和结束日期。

根据当前日期的位置,计算上周和下周的日期范围

const moment = require('moment');
// 或者 import moment from 'moment'

calculateWeekPeriods() {
    const today = moment();
    const dayOfWeek = today.isoWeekday();

    // 计算本周的起始日期和结束日期
    const startDateThisWeek = today.clone().startOf('isoWeek');
    const endDateThisWeek = today.clone().endOf('isoWeek');

    // 计算上周和下周的起始日期和结束日期
    const startDateLastWeek = startDateThisWeek.clone().subtract(1, 'week');
    const endDateLastWeek = startDateLastWeek.clone().endOf('isoWeek');
    const startDateNextWeek = startDateThisWeek.clone().add(1, 'week');
    const endDateNextWeek = startDateNextWeek.clone().endOf('isoWeek');

    // 格式化日期范围
    const formatDateRange = (startDate, endDate) => {
        return `${startDate.format('YYYY-MM-DD')}~${endDate.format('YYYY-MM-DD')}`;
    };

    // 生成周期数组
    const weekPeriods = [
        { label: '上周', dateRange: formatDateRange(startDateLastWeek, endDateLastWeek) },
        { label: '这周', dateRange: formatDateRange(startDateThisWeek, endDateThisWeek) },
        { label: '下周', dateRange: formatDateRange(startDateNextWeek, endDateNextWeek) }
    ];

    this.weekPeriods = weekPeriods;
}

通过ES6 中的箭头函数、模板字符串等语法,更加完好的展示如下功能:

// 获取当前日期和时间,包括年、月、日、周几、时、分、秒
const getCurrentDateTime = () => {
    const now = new Date();
    const year = now.getFullYear();
    let month = now.getMonth() + 1;
    let date = now.getDate();
    const day = now.getDay();
    let hour = now.getHours();
    let minu = now.getMinutes();
    let sec = now.getSeconds();

    // 格式化月份、日期、小时、分钟、秒数,保证两位数
    month = month < 10 ? "0" + month : month;
    date = date < 10 ? "0" + date : date;
    hour = hour < 10 ? "0" + hour : hour;
    minu = minu < 10 ? "0" + minu : minu;
    sec = sec < 10 ? "0" + sec : sec;

    // 返回格式化后的字符串
    return `${year}-${month}-${date}${day} 时间: ${hour}:${minu}:${sec}`;
};

// 获取当前日期
const getCurrentDate = () => {
    const startDate = new Date();
    const year = startDate.getFullYear();
    let month = startDate.getMonth() + 1;
    let day = startDate.getDate();

    // 格式化月份、日期,保证两位数
    month = month < 10 ? "0" + month : month;
    day = day < 10 ? "0" + day : day;

    // 返回格式化后的字符串
    return `${year}-${month}-${day}`;
};

// 获取当前日期减去指定天数的日期
const getDateMinusDays = (days) => {
    const nowDate = new Date();
    nowDate.setDate(nowDate.getDate() - days);
    const year = nowDate.getFullYear();
    let month = nowDate.getMonth() + 1;
    let date = nowDate.getDate();

    // 格式化月份、日期,保证两位数
    month = month < 10 ? "0" + month : month;
    date = date < 10 ? "0" + date : date;

    // 返回格式化后的字符串
    return `${year}-${month}-${date}`;
};

// 获取当前日期加上指定天数的日期
const getDatePlusDays = (days) => {
    const nowDate = new Date();
    nowDate.setDate(nowDate.getDate() + days);
    const year = nowDate.getFullYear();
    let month = nowDate.getMonth() + 1;
    let date = nowDate.getDate();

    // 格式化月份、日期,保证两位数
    month = month < 10 ? "0" + month : month;
    date = date < 10 ? "0" + date : date;

    // 返回格式化后的字符串
    return `${year}-${month}-${date}`;
};

// 获取当前日期加减指定天数的日期与具体时间点(时间戳获取)
const getDatePlusMinusDaysWithTime = (days, isPlus = true) => {
    const timestamp = new Date().getTime() / 1000;
    const adjustedTimestamp = isPlus ? timestamp + (60 * 60 * 24 * days) : timestamp - (60 * 60 * 24 * days);
    const adjustedDate = new Date(adjustedTimestamp * 1000);
    const year = adjustedDate.getFullYear();
    let month = adjustedDate.getMonth() + 1;
    let date = adjustedDate.getDate();
    let hour = adjustedDate.getHours();
    let minu = adjustedDate.getMinutes();
    let sec = adjustedDate.getSeconds();

    // 格式化月份、日期、小时、分钟、秒数,保证两位数
    month = month < 10 ? "0" + month : month;
    date = date < 10 ? "0" + date : date;
    hour = hour < 10 ? "0" + hour : hour;
    minu = minu < 10 ? "0" + minu : minu;
    sec = sec < 10 ? "0" + sec : sec;

    // 返回格式化后的日期与时间点
    return `${year}-${month}-${date} ${hour}:${minu}:${sec}`;
};

// 示例:获取当前日期和时间
const currentDateTime = getCurrentDateTime();
console.log("当前日期和时间:", currentDateTime);

// 示例:获取当前日期
const currentDate = getCurrentDate();
console.log("当前日期:", currentDate);

// 示例:获取当前日期减去7天的日期
const dateMinus7Days = getDateMinusDays(7);
console.log("当前日期减去7天的日期:", dateMinus7Days);

// 示例:获取当前日期加上7天的日期
const datePlus7Days = getDatePlusDays(7);
console.log("当前日期加上7天的日期:", datePlus7Days);

// 示例:获取当前日期加减7天的日期与具体时间点(时间戳获取)
const datePlusMinus7DaysWithTime = getDatePlusMinusDaysWithTime(7);
console.log("当前日期加7天的日期与具体时间点:", datePlusMinus7DaysWithTime);

const dateMinusMinus7DaysWithTime = getDatePlusMinusDaysWithTime(7, false);
console.log("当前日期减7天的日期与具体时间点:", dateMinusMinus7DaysWithTime);

3. 彩蛋

此处给出Java后端的写法:

// 获取当前日期
LocalDate currentDate = LocalDate.now();

// 获取本周的起始日期和结束日期
LocalDate startDateThisWeek = currentDate.with(DayOfWeek.MONDAY);
LocalDate endDateThisWeek = currentDate.with(DayOfWeek.SUNDAY);

// 获取上周的起始日期和结束日期
LocalDate startDateLastWeek = startDateThisWeek.minusWeeks(1);
LocalDate endDateLastWeek = endDateThisWeek.minusWeeks(1);

// 获取下周的起始日期和结束日期
LocalDate startDateNextWeek = startDateThisWeek.plusWeeks(1);
LocalDate endDateNextWeek = endDateThisWeek.plusWeeks(1);

对于Java的基本知识推荐阅读:java框架 零基础从入门到精通的学习路线 附开源项目面经等(超全)

最近更新

  1. TCP协议是安全的吗?

    2024-04-14 04:02:01       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-14 04:02:01       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-14 04:02:01       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-14 04:02:01       18 阅读

热门阅读

  1. RTK高精度定位

    2024-04-14 04:02:01       14 阅读
  2. LeetCode 139. 单词拆分

    2024-04-14 04:02:01       13 阅读
  3. 人工智能技术的创业机遇

    2024-04-14 04:02:01       14 阅读
  4. [ LeetCode ] 题刷刷(Python)-第49题:字母异位词分组

    2024-04-14 04:02:01       13 阅读
  5. 如何在Python中实现设计模式?

    2024-04-14 04:02:01       15 阅读
  6. C动\静态库编译

    2024-04-14 04:02:01       14 阅读
  7. python3面向对象

    2024-04-14 04:02:01       14 阅读
  8. pyqt写个星三角降压启动方式2

    2024-04-14 04:02:01       13 阅读
  9. postgis使用

    2024-04-14 04:02:01       16 阅读
  10. photoshop基础学习笔记

    2024-04-14 04:02:01       13 阅读