记录 js 通用方法

18 篇文章 0 订阅

//获取时间、星期、时段 js的效果图
在这里插入图片描述


 //获取时间、星期、时段
      setNowTimes() {
        let myDate = new Date()
        let wk = myDate.getDay()
        let yy = String(myDate.getFullYear())
        let mm = myDate.getMonth() + 1
        let dd = String(myDate.getDate() < 10 ? '0' + myDate.getDate() : myDate.getDate())
        let hou = String(myDate.getHours() < 10 ? '0' + myDate.getHours() : myDate.getHours())
        let min = String(myDate.getMinutes() < 10 ? '0' + myDate.getMinutes() : myDate.getMinutes())
        let sec = String(myDate.getSeconds() < 10 ? '0' + myDate.getSeconds() : myDate.getSeconds())
        let weeks = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
        let week = weeks[wk];
        // 获取当前小时
        let hours = myDate.getHours();
        // 设置默认文字
        let state= ``;
        // 判断当前时间段
        if (hours >= 0 && hours <= 10) {
          state = `上午`;
        } else if (hours > 10 && hours <= 14) {
          state= `中午好`;
        } else if (hours > 14 && hours <= 18) {
          state= `下午好`;
        } else if (hours > 18 && hours <= 24) {
          state= `晚上好`;
        }
        this.nowTimeState = state;//时段
        this.nowDate = yy + '年' + mm + '月' + dd + '日';//日期
        // this.nowTime = hou + ':' + min + ':' + sec
        this.nowWeek = week;//星期
      },
      
      
/**
 * 判断当前时间处于某个时间段
 * @param beginTime 开始时间 eg:9:00
 * @param endTime 结束时间 eg: 12:00
 *
 * @return Boolean
 * */
export function checkAuditTime(beginTime, endTime) {
  var nowDate = new Date();
  var beginDate = new Date(nowDate);
  var endDate = new Date(nowDate);

  var beginIndex = beginTime.lastIndexOf("\:");
  var beginHour = beginTime.substring(0, beginIndex);
  var beginMinue = beginTime.substring(beginIndex + 1, beginTime.length);
  beginDate.setHours(beginHour, beginMinue, 0, 0);

  var endIndex = endTime.lastIndexOf("\:");
  var endHour = endTime.substring(0, endIndex);
  var endMinue = endTime.substring(endIndex + 1, endTime.length);
  endDate.setHours(endHour, endMinue, 0, 0);
  return nowDate.getTime() - beginDate.getTime() >= 0 && nowDate.getTime() <= endDate.getTime();
}
/*
* 获取本周时间段
* @author YYH
* */
export function getWeekTime() {
  const one_day = 86400000;// 24 * 60 * 60 * 1000;
  const date = new Date();
  const day = date.getDay();// 返回0-6,0表示周日
  // 设置时间为当天的0点
  date.setHours(0);
  date.setMinutes(0);
  date.setSeconds(0);
  date.setMilliseconds(0);
  let week_start_time = ISO_FormatTime(new Date(date.getTime() - (day - 1) * one_day))
  let week_end_time = ISO_FormatTime(new Date(date.getTime() + (7 - day) * one_day))
  week_start_time  = week_start_time.substr(0,week_start_time.indexOf(' '))
  week_end_time  = week_end_time.substr(0,week_end_time.indexOf(' '))
  return {
    week_start_time,
    week_end_time
  }
}
/**
 * 对象数组/数组 循环去重
 * @author YYH
 * @params {Array or Object}
 * @returns {Array or Object}
 */
export function filterSet(arr){
    for (let i = 0; i < arr.length; i++) {
      for (let j = i + 1; j < arr.length; j++) {
        //如果是数组这里判断不要参数名就可以了
        if (arr[i].schedulingDate == arr[j].schedulingDate) { 
          arr.splice(j, 1);
          j--;
        }
      }
    }
    return arr;
}

/**
 * 过滤对象中为空的属性
 * @param obj
 * @returns {*}
 */
export function filterObj(obj) {
  if (!(typeof obj == 'object')) {
    return;
  }

  for ( let key in obj) {
    if (obj.hasOwnProperty(key)
      && (obj[key] == null || obj[key] == undefined || obj[key] === '')) {
      delete obj[key];
    }
  }
  return obj;
}


/**
 * 将ISO时间格式转换为YYYY-MM-DD hh:mf:ss格式
 * @author YOUYUHAO
 * @param1 UTC格式 第一个数
 * @returns YYYY-MM-DD hh:mf:ss
 */
export function ISO_FormatTime(originVal) {
  const date =  new Date(originVal);
  const y = date.getFullYear();
  const m = "0"+(date.getMonth()+1);
  const d = "0"+date.getDate();
  const h = date.getHours();
  const mm = date.getMinutes();
  const s = date.getSeconds();
  return `${y}-${m.substring(m.length-2,m.length)}-${d.substring(d.length-2,d.length)} ${h}:${mm}:${s}`; // 2021-09-14 19:36:10
  // return `${y}-${m.substring(m.length-2,m.length)}-${d.substring(d.length-2,d.length)}`;  //2021-09-14
}

/**
 * 判断当前传入字符串是否是ISO格式日期
 * @author YOUYUHAO
 * @param1 string
 * @returns boolean
 */
export function isISODate(str) {
  if (!/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z/.test(str)) return false;
  let d = new Date(str);
  return d.toISOString()===str;
}

/**
 * 根据年份计算总周数
 * @param year
 * @returns {number}
 */
export function getNumOfWeeks(year) {
  //设置为这一年开始日期
  var startDateOfYear = new Date(year, 0, 1);
  console.log("startDateOfYear::",startDateOfYear)
  //计算这一年有多少天
  var daysOfYear = ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) ? 366 : 365;
  //366(365)/7=52.2(52.1),所以一般一年有52周余1天或者2天,当这一年有366天时且第一天是周日,那么他的最后一天则是周一,这一年就有54周。
  var weekNum = 53;
  //当年份是闰年且第一天是周日时有54周
  if (startDateOfYear.getDay() == 0 && daysOfYear == 366) {
    weekNum = 54;
  }
  return weekNum;
}


/**
 * 根据当前时间判断在本年的第几周
 * @author YYH
 * @returns {number}
 */
export function getWeekNum() {
  //获得当前日期是第几周的方法
  var year = new Date().getFullYear();
  var week = moment(new Date()).format("E");//获得今天是星期几

  var startweek = moment(new Date(year + "-01-01")).format("E");//获得今年的1月1号是星期几
  //今天到1月1号的时间戳之差
  var millisDiff =
    new Date(moment().format("yyyy-MM-DD")).getTime() -
    new Date(year + "-01-01").getTime();
  var days =
    (millisDiff -
      week * (24 * 60 * 60 * 1000) -
      (7 - startweek) * (24 * 60 * 60 * 1000)) /
    86400000;
  return days / 7 + 2;
  //这里加的2代表的是本周和今年1月1号所在的那一周
}


/**
 * 根据上周日获取这周日的日期范围
 * @param lastSunday
 * @returns {string}
 */
export function getDateRange(lastSunday) {
  if (lastSunday == null || lastSunday == '') {
    return "";
  }
  let beginDate = new Date(lastSunday.setDate(lastSunday.getDate() + 1));
  let endDate = new Date(lastSunday.setDate(lastSunday.getDate() + 6));
  return '(' + getNowFormatDate(beginDate) + ')-' + '(' + getNowFormatDate(endDate) + ')';
}



/**
 * 时间转换成字符串
 * @param date
 * @returns {string}
 */
export function getNowFormatDate(date) {
  let Month = 0;
  let Day = 0;
  let CurrentStr = "";
  // 初始化时间
  Month = date.getMonth() + 1;
  Day = date.getDate();
  if (Month >= 10) {
    CurrentStr += Month + "月";
  } else {
    CurrentStr += "0" + Month + "月";
  }
  if (Day >= 10) {
    CurrentStr += Day + "日";
  } else {
    CurrentStr += "0" + Day + "日";
  }
  return CurrentStr;
}


/**
 * 判断第一个日期 是否大于 第二个日期
 * @author YYH
 * @param1 DateFront 第一个数
 * @param2 DateAfter 第二个数
 * @param3 format 比较格式 YYYY-MM-DD-hh-mf-ss??
 * @returns {Boolean}
 */
export function CompareDateSize(DateFront,DateAfter,format){
  return Date.parse(formatDate(DateFront,format)) >= Date.parse(formatDate(DateAfter,format))
}

/**
 * 获取当前时间 YYYY-MM
 *  @author YYH
 *  @param format 格式
 * @returns {YYYY-MM}
 */
export function getCurrentTime(format) {
  //获取当前时间并打印
  let yy = new Date().getFullYear();
  let mm = new Date().getMonth()+1;
  if(mm < 10){
    mm = "0"+mm;
  }
  let dd = new Date().getDate();
  if(dd < 10){
    dd = "0"+dd;
  }
  let hh = new Date().getHours();
  let mf = new Date().getMinutes()<10 ? '0'+new Date().getMinutes() : new Date().getMinutes();
  let ss = new Date().getSeconds()<10 ? '0'+new Date().getSeconds() : new Date().getSeconds();
  let getTime = yy+'-'+mm+'-'+dd+'-'+hh+'-'+mf+'-'+ss;
  getTime = formatDate(getTime,format)
  return getTime;
}

/**
 * 时间格式化
 * @param value
 * @param fmt
 * @returns {*}
 */
export function formatDate(value, fmt) {
  let regPos = /^\d+(\.\d+)?$/;
  if(regPos.test(value)){
    //如果是数字
    let getDate = new Date(value);
    let o = {
      'M+': getDate.getMonth() + 1,
      'd+': getDate.getDate(),
      'h+': getDate.getHours(),
      'm+': getDate.getMinutes(),
      's+': getDate.getSeconds(),
      'q+': Math.floor((getDate.getMonth() + 3) / 3),
      'S': getDate.getMilliseconds()
    };
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (getDate.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    for (let k in o) {
      if (new RegExp('(' + k + ')').test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
      }
    }
    return fmt;
  }else{
    //TODO
    value = value.trim();
    return value.substr(0,fmt.length);
  }
}

/**
 * 循环对象数组,判断对象数组中每一项字段是否是moment,如果是则转为yyyy-mm-dd hh:mm:ss格式,并将数组返回
 * @author YOUYUHAO
 * @param1 ArrayObject
 * @returns ArrayObject
 */
export function arrayDataHasISO_ToDate(ObjectData = []){
  return new Promise((rej,res) => {
    ObjectData.map(i => {
      Object.keys(i).map(j => {
        if (typeof (i[j]) === 'object') {
          if ('_isAMomentObject' in i[j]) {
            if (i[j]._isAMomentObject) {
              i[j] = ISO_FormatTime(i[j])
            }
          }
        }
      })
    });
    rej(ObjectData)
  })
}


/**
 * 循环对象,判断对象中每一项字段是否是moment,如果是则转为yyyy-mm-dd hh:mm:ss格式,并将数组返回
 * @author YOUYUHAO
 * @param1 Object
 * @returns Object
 */
export function ObjectDataHasISO_ToDate(ObjectData = {}){
  return new Promise((rej,res) => {
      Object.keys(ObjectData).map(j => {
        if (typeof (ObjectData[j]) === 'object') {
          if ('_isAMomentObject' in ObjectData[j]) {
            if (ObjectData[j]._isAMomentObject) {
              ObjectData[j] = ISO_FormatTime(ObjectData[j])
            }
          }
        }
      })
    rej(ObjectData)
  })
}


使用方式:
let newData = [{},{}];//对象数组
let modelFormData = {};//对象
arrayDataHasISO_ToDate(newData).then(res=>{
        newData = res;
      })
      ObjectDataHasISO_ToDate(modelFormData).then(res=>{
        modelFormData = res;
      })

日期禁用:

<a-date-picker v-model="timeObject" :disabledDate="disabledDate" />

 //限制当天之后的日期不可选
    disabledDate(current) {
      return current && current >moment().subtract(0, "days");//当天之后的不可选,不包括当天
      //return current && current < moment().endOf(‘day');当天之后的不可选,包括当天
    },
    //限制当天之前的日期不可选
      disabledDate(current) {
        return current && current <moment().subtract(1, "days"); //当天之前的不可选,不包括当天
        //return current && current < moment().endOf(‘day');当天之前的不可选,包括当天
      },
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值