js获取当前时间和前30天的日期

JavaScript 中的 Date 对象使用毫秒数来表示时间。因此,一天(24 小时)的毫秒数是:

const MS_PER_DAY = 24 * 60 * 60 * 1000;

计算三十天后的日期:

let currentDate = new Date();//当前时间
let thirtyDaysLater = new Date(currentDate.getTime() + (30 * MS_PER_DAY));//当前时间 + 30天的以秒计算的单位时间
console.log(
"Date Thirty Days Later:", thirtyDaysLater);

计算三十天前的日期:

    // 获取当前日期
    const currentDate = new Date();
    // 获取30天前的日期 (30*24*60*60*1000)30:指周期,24:指一天24小时,60:指一小时60分钟,60:一分钟60s,1000:1秒=1000ms
    const thirtyDaysAgo = new Date(currentDate.getTime() - (30 * 24 * 60 * 60 * 1000));

输出日期周期范围

   // 格式化日期为YYYY-MM-DD
    const formatDate = (date) => {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      return `${year}-${month}-${day}`;
    };

    // 计算开始日期和结束日期
    const formattedDate = formatDate(thirtyDaysAgo); //起始日期
    const aftertime = formatDate(currentDate);//结束日期

其他详细使用请参考 https://my.oschina.net/emacs_8498174/blog/16527733

posted @ 2025-01-06 13:38  3939!  阅读(618)  评论(0)    收藏  举报