zoukankan      html  css  js  c++  java
  • js根据当前日期提前N天或推后N天的方法

    先提供2个方法,根据当前日期转化年月日方法

    export function formatDate(date) {
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      return [year, month, day].map(formatNumber).join('-');
    }
    export function formatDateBegin(date) {
      const year = date.getFullYear();
      const month = date.getMonth();
      const day = date.getDate();
      return [year, month, day].map(formatNumber).join('-');
    }

    提前N天或推后N天的方法,返回时间戳

    /*
    *now  为当前时间new Date()
    *d为天数,提前3天,传-3
    * 推后3天,传3
    **/
    export function defaulTime(now, d) {
      now.setHours(0);
      now.setMinutes(0);
      now.setSeconds(0);
      now.setDate(now.getDate() + d);
      now = now.getTime();
      return now;
    }

    console.log(defaulTime(new Date(),-24),defaulTime(new Date(),6));  //提前24天和推后6天,返回时间戳
     

    提前N天或推后N天的方法,返回年月日,

    注:我这个方法把当前时间的时分秒设为了0,如果不需要注释即可

    /*
    *now  为当前时间new Date()
    *d为天数,提前传负数,推后传正数
    * 提前3天,传-3
    * 推后3天,传3
    **/
    export function defaulTime2(now, d) {
      //把时分秒设置为0,不需要就直接注释掉就好了
      now.setHours(0);
      now.setMinutes(0);
      now.setSeconds(0);
      now.setDate(now.getDate() + d);
      now = formatDate(now);  //用了上面转年月日的方法
      // now = now.toLocaleDateString(); //自带的年月小于10时,没有自动补0,所以用了自己的方法,看自己需要
    return now;
    }

    console.log(
    defaulTime2(new Date(),-24),defaulTime2(new Date(),6)); //提前24天和推后6天,返回日期

      

  • 相关阅读:
    python基础语法_9-2函数式编程
    python基础语法_9-1闭包 装饰器补充
    python基础语法_9-0函数概念
    python基础语法_8循环语句
    python基础语法_7运算符
    python基础语法_3面向对象
    python基础语法_2基本数据类型
    python基础语法_python中的布尔类型详解
    用户需求分析
    结对编程-词频统计(北航暑期软工培训) 郑琪 李泓毅
  • 原文地址:https://www.cnblogs.com/tanweiwei/p/12849302.html
Copyright © 2011-2022 走看看