微信小程序 常用函數

1. 獲取本週日期

一週日期顯示
note:上週日到這週六的日期
result: getWeeks()接收參數爲時間格式,返回的是關於日期的一個數組 [2019-02-17,2019-02-18,…]
getDates() 返回日期的數組[17,18,19…]

  const UTIL = require('../../../utils/util.js');
  getDates() {
  	let nowDate = new Date()
    let timesStamp = nowDate.getTime();
    let currenDay = nowDate.getDay();
    let dates = [];
    // 減去的一是爲了獲取包括上週日的時間數組
    for (var i = 0; i < 7; i++) {
      dates.push(new Date(timesStamp + 24 * 60 * 60 * 1000 * (i - (currenDay + 6) % 7 - 1)).getDate());
    }
    return dates
  },
  getWeeks(nowDate) {
  	let nowDate = new Date()
    let timesStamp = nowDate.getTime();
    let currenDay = nowDate.getDay();
    let weekDates = [];
    for (var i = 0; i < 7; i++) {
      weekDates.push(UTIL.timeStampToYMD(timesStamp + 24 * 60 * 60 * 1000 * (i - (currenDay + 6) % 7 - 1)));
    }
    return weekDates
  },  

引用中的timeStampToYMD時間戳轉化成yyyy-mm-dd格式函數:

	const timeStampToYMD = timeStamp => {
	  var date = new Date(timeStamp);
	  return formatTime(date).slice(0, formatTime(date).indexOf(' ')).replace(/\//g, '-');
	}
	const formatTime = date => {
	  const year = date.getFullYear()
	  const month = date.getMonth() + 1
	  const day = date.getDate()
	  const hour = date.getHours()
	  const minute = date.getMinutes()
	  const second = date.getSeconds()
	
	  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
	}
	module.exports = {
	  formatTime: formatTime,
	  timeStampToYMD: timeStampToYMD
  }

2. 時間戳轉化成年月日、分時秒

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
// 時間戳轉化成 年月日
const timeStampToYMD = timeStamp => {
  var date = new Date(timeStamp);
  return formatTime(date).slice(0, formatTime(date).indexOf(' ')).replace(/\//g, '-');
}
// 時間戳轉化成 分時秒
const timeStampToHMS = timeStamp => {
  var date = new Date(timeStamp);
  return formatTime(date).slice(formatTime(date).indexOf(' ') + 1);
}

2. checkbox 限制最多選擇的個數

project 數組結構 爲 [{“value”:“購物”;“isSelected”:false},{“value”:“逛街”;“isSelected”:false}]

  <checkbox-group wx:for="{{project}}" wx:key="{{index}}" bindchange="checkboxChange" data-index='{{index}}'>
    <checkbox value='{{item.value}}' disabled="{{isMoreItem && !item.isSelected}}">{{item.value}}</checkbox>
  </checkbox-group>

isMoreItem初始值爲false,當 totalNum 中選中的數組個數大於5個時,islimitItem爲true 則新的未選擇的不可選。

  // 選中
  checkboxChange(e) {
    let project = this.data.project;
    let index = e.currentTarget.dataset.index;
    project[index].isSelected = !project[index].isSelected;
    this.setData({
      project: project
    })
    let totalNum = project.filter((value)=>{
      return value.isSelected
    }).length
    
    if (totalNum > 4) {
      wx.showToast({
        title: '最多不能超過5項',
        icon: 'none'
      })
      this.setData({
        islimitItem: true
      })
    } else {
      this.setData({
        islimitItem: false
      })
    }
    console.log("totalNum*****", totalNum, "islimitItem", this.data.islimitItem)
  },

4. //判斷已經出生多少年、多少月、多少日

接收一個數組: birthday 格式爲 2019-03-11
嬰兒[0,2) 兒童 [2,12) 成人12以上 return 3,2,1


  judgeAge(birthday) {
    let ageObj = {};
    let date = birthday.replace(/-/g, '/'); // 字符轉化 兼容IOS
    let birth = new Date(`${date} 00:00:00`) //拼接時間
    let now = new Date()
    let yearDiff = now.getFullYear() - birth.getFullYear()
    let monthDiff = now.getMonth() - birth.getMonth()
    let dayDiff = now.getDate() - birth.getDate()
    if (birth.getTime() > now.getTime()) {
      return false;
    }
    // 嬰兒[0,2) 兒童 [2,12) 成人[12以上 return 3,2,1
    const babyYear = 2
    const adultYear = 12
    if (yearDiff == babyYear) {
      return this.currentDateResult(monthDiff, dayDiff, 3, 2)
    } else if (yearDiff == adultYear) {
      return this.currentDateResult(monthDiff, dayDiff, 2, 1)
    } else if (yearDiff > babyYear && yearDiff < adultYear) {
      return 2;
    } else {
      return yearDiff < babyYear ? 3 : yearDiff > adultYear ? 1 : 2;
    }
  },
  currentDateResult(monthDiff, dayDiff, oneResult, twoResult) {
    if (monthDiff == 0) {
      return dayDiff < 0 ? oneResult : twoResult;
    } else {
      return monthDiff < 0 ? oneResult : twoResult;
    }
  },

5. 小數點保留 位數

toFixed() 使用的是銀行家舍入規則:四捨六入五取偶(又稱四捨六入五留雙)。
(0.015).toFixed(2); // 0.01 ,

// 保留n位小數並格式化輸出(不足的部分補0)
var fomatFloat = function(value, n) {
    var f = Math.round(value*Math.pow(10,n))/Math.pow(10,n);
    var s = f.toString();
    var rs = s.indexOf('.');   
    if (rs < 0) {     
        s += '.';   
    } 
    for(var i = s.length - s.indexOf('.'); i <= n; i++){
      s += "0";
    }
    return s;
}
//var num3 = fomatFloat(0.015, 2);  // 0.02

6. 清除爲undefined的空數組

  // 移除未定義的數組
  removeEmptyArrayEle(arr) {
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] == undefined) {
        arr.splice(i, 1);
        i = i - 1;
      }
    }
    return arr
  },
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章