JavaScript方法函数记录

系统方法函数

// 编码:encodeURI("张童瑶")
// 结果:"%E5%BC%A0%E7%AB%A5%E7%91%B6"

// 解码:decodeURI("%E5%BC%A0%E7%AB%A5%E7%91%B6")
// 结果:"张童瑶"

// 对象转数组:JSON.stringify(obj)

时间方法函数

获得指定月的开始结束日期

/**
 * 获得指定月的开始结束日期
 * 用法:getMonthStartEndDate("2020-01")
 * @param vars
 * @returns {Array}
 */
function getMonthStartEndDate(vars){
    vars = vars.replace("-","");
    var array = [];
    if(vars!=null&&vars!=''){
        var nyYear=vars.slice(0,4);
        var nyMonth=vars.slice(4,vars.length);
        var firstDay = new Date(nyYear,nyMonth-1);
        var lastDay = new Date(new Date(nyYear,nyMonth).valueOf()-60*60*1000*24);
        function datasFormat(d){
            var datetime=d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
            return datetime;
        }
        array[0] = datasFormat(firstDay);
        array[1] = datasFormat(lastDay);
    }
    return array
};

获得上周开始结束日期

function getUpWeekStartEndDate() {
	//var now = new Date(2016,3,18) //根据指定日期,获取周的开始结束日期
	var now = new Date();
	var weekStartDate = new Date(
	now.getFullYear(),
	now.getMonth(),
	now.getDate() - now.getDay() - 6);
	
	var myyear = weekStartDate.getFullYear();
	var mymonth = weekStartDate.getMonth() + 1;
	var myweekday = weekStartDate.getDate();
	if (mymonth < 10) {
		mymonth = "0" + mymonth;
	}
	if (myweekday < 10) {
		myweekday = "0" + myweekday;
	}
	var array = [];
    array[0] = myyear + "-" + mymonth + "-" + myweekday
    
	var weekStartDate = new Date(
	now.getFullYear(),
	now.getMonth(),
	now.getDate() - now.getDay());
	
	var myyear = weekStartDate.getFullYear();
	var mymonth = weekStartDate.getMonth() + 1;
	var myweekday = weekStartDate.getDate();
	
	if (mymonth < 10) {
		mymonth = "0" + mymonth;
	}
	if (myweekday < 10) {
		myweekday = "0" + myweekday;
	}
	array[1] = myyear + "-" + mymonth + "-" + myweekday
	return array;
}

根据开始结束日期获得中间所有天数

/**
 * 根据开始结束日期获得中间所有天数
 * 用法:
 *  1、byStartEndDateGetMiddleDate("2020-1-1","2020-1-5")
 *  2、byStartEndDateGetMiddleDate("2020-1","2020-5")
 *  3、byStartEndDateGetMiddleDate("2020","2022")
 * @param startTime 开始日期
 * @param endTime   结束日期
 * @returns {Array}
 */
function byStartEndDateGetMiddleDay(startDate,endDate){
    var bd = new Date(startDate),be = new Date(endDate);
    var bd_time = bd.getTime(), be_time = be.getTime(),time_diff = be_time - bd_time;
    var d_arr = [];
    for(var i=0; i<= time_diff; i+=86400000){
        var ds = new Date(bd_time+i);
        d_arr.push(ds.getFullYear()+'-'+(ds.getMonth()+1)+'-'+ds.getDate()+'')
    }
    return d_arr;
}

获取从开始时间到结束时间中的所有月

/**
 * 获取从开始时间到结束时间中的所有月
 * 用法:
 *  1、byStartEndDateGetMiddleMonthDate("2020-1-1","2020-6-1")
 *  2、byStartEndDateGetMiddleMonthDate("2020-1","2020-6")
 * @param startDate
 * @param endDate
 * @returns {array}
 */
function byStartEndDateGetMiddleMonth(startDate,endDate) {
    var d1 = startDate;
    var d2 = endDate;
    var dateArry = new Array();
    var s1 = d1.split("-");
    var s2 = d2.split("-");
    var mCount = 0;
    if (parseInt(s1[0]) < parseInt(s2[0])) {
        mCount = (parseInt(s2[0]) - parseInt(s1[0])) * 12 + parseInt(s2[1]) - parseInt(s1[1])+1;
    } else {
        mCount = parseInt(s2[1]) - parseInt(s1[1])+1;
    }
    if (mCount > 0) {
        var startM = parseInt(s1[1]);
        var startY = parseInt(s1[0]);
        for (var i = 0; i < mCount; i++) {
            if (startM < 12) {
                dateArry[i] = startY + "-" + (startM>9 ? startM : "0" + startM);
                startM += 1;
            } else {
                dateArry[i] = startY + "-" + (startM > 9 ? startM : "0" + startM);
                startM = 1;
                startY += 1;
            }
        }
    }
    return dateArry;
}

根据开始结束日期获取中间的所有年

/**
 * 根据开始结束日期获取中间的所有年
 * 用法:
 *  1、byStartEndDateGetMiddleYear("2020-1-1","2021-1-1")
 *  2、byStartEndDateGetMiddleYear("2020-1","2021-1")
 *  3、byStartEndDateGetMiddleYear("2020","2021")
 * @param startDate
 * @param endDate
 * @returns {any[]}
 */
function byStartEndDateGetMiddleYear(startDate,endDate) {
    var d1 = startDate;
    var d2 = endDate;
    var dateArry = new Array();
    var s1 = d1.split("-");
    var s2 = d2.split("-");
    var mYearCount = parseInt(s2[0]) - parseInt(s1[0])+1;
    var startY = parseInt(s1[0]);
    for (var i = 0; i < mYearCount;i++) {
        dateArry[i] = startY;
        startY += 1;
    }
    return dateArry;
};

根据指定日期,获取星期几

/**
 * 根据指定日期,获取星期几
 * 用法:byDateGetWeek("2020-1-5")
 * @param dateString
 * @returns {string}
 */
function byDateGetWeek(dateString) {
    var dateArray = dateString.split("-");
    date = new Date(dateArray[0], parseInt(dateArray[1] - 1), dateArray[2]);
    return "周" + "日一二三四五六".charAt(date.getDay());
};

获取年的开始日期和结束日期

/**
 * 获取年的开始日期和结束日期
 * @param vars
 * @returns {string}
 */
function getYearStartEndDate(vars){
    var array = [];
    array[0] = vars+"-01-01";
    array[1] = vars+"-12-31";
    return array;
}

获得前几天后几天日期

/**
 * 获得前几天后几天日期
 * @param vars
 * @returns {string}
 */
function getNextDate(date,day) {  
  var dd = new Date(date);
  dd.setDate(dd.getDate() + day);
  var y = dd.getFullYear();
  var m = dd.getMonth() + 1 < 10 ? "0" + (dd.getMonth() + 1) : dd.getMonth() + 1;
  var d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate();
  return y + "-" + m + "-" + d;
};
getNextDate("2018-09-27",10)

Fri Dec 12 2014 08:00:00 GMT+0800日期转换格式

/**
 * Fri Dec 12 2014 08:00:00 GMT+0800日期转换格式
 * 用法:formateDate("Fri Dec 12 2014 08:00:00 GMT+0800")
 * @param str
 * @returns {string}
 */
function formateDate(str){
    var formate = new Date(str);
    return formate.getFullYear() + '-' + (formate .getMonth() + 1) + '-' + formate .getDate() + ' ' + formate .getHours() + ':' + formate.getMinutes() + ':' + formate.getSeconds();
}

处理单数日期

/**
 * 处理单数日期
 * 用法:formatSingularDate("2020-1-2")
 * 返回:2020-01-02
 * @param str
 * @returns {string}
 */
function formatSingularDate(time){
	var array = time.split('-')
    var month = parseInt(array[1]);
    if(month <= 9){
       array[1] = "0" + month
    }
    
    var day = parseInt(array[2]);
    if(day <= 9){
       array[2] = "0" + day
    }
    return array[0]+"-"+array[1]+"-"+array[2]
}

js自带new Date()函数 详解

var gettime = new Date(); //创建获取当前时间函数
gettime.getYear(); //获取当前年份 (2位) 
gettime.getFullYear(); //获取完整的年份 (4位)
gettime.getMonth(); //获取月份 (0-11月,0是1月)
gettime.getDate(); //获取当前日期 (1-31日)
gettime.getTime(); //获取当前时间  (从1970.1.1开始的毫秒数)
gettime.getDay(); //获取当前星期X (0-6,0是星期天)
gettime.getHours(); //获取当前小时数 (0-23)
gettime.getMinutes(); //获取当前分钟数 (0-59)
gettime.getSeconds(); //获取当前秒  (0-59) 
gettime.getMilliseconds(); //获取当前毫秒数 (0-999)
gettime.toLocaleDateString(); //获取当前日期 
gettime.toLocaleTimeString(); //获取当前时间
gettime.toLocalString(); //获取当前日期与时间 

var gettime = new Date(2020,11,1); //创建2020年的时间对象函数

var new_date = new Date(2020,11,1); //取当年当月中的第一天
(new Date(new_date.getTime()-1000*60*60*24)).getDate();//获取当月最后一天日期

时间操作的大杂烩

/**
 * 获取本周、本季度、本月、上月的开始日期、结束日期
 */
var now = new Date(); //当前日期
var nowDayOfWeek = now.getDay(); //今天本周的第几天
var nowDay = now.getDate(); //当前日
var nowMonth = now.getMonth(); //当前月
var nowYear = now.getYear(); //当前年
nowYear += (nowYear < 2000) ? 1900 : 0; //
var lastMonthDate = new Date(); //上月日期
lastMonthDate.setDate(1);
lastMonthDate.setMonth(lastMonthDate.getMonth() - 1);
var lastYear = lastMonthDate.getYear();
var lastMonth = lastMonthDate.getMonth();
//格式化日期:yyyy-MM-dd
function formatDate(date) {
  var myyear = date.getFullYear();
  var mymonth = date.getMonth() + 1;
  var myweekday = date.getDate();
  if (mymonth < 10) {
    mymonth = "0" + mymonth;
  }
  if (myweekday < 10) {
    myweekday = "0" + myweekday;
  }
  return (myyear + "-" + mymonth + "-" + myweekday);
}
//获得某月的天数
function getMonthDays(myMonth) {
  var monthStartDate = new Date(nowYear, myMonth, 1);
  var monthEndDate = new Date(nowYear, myMonth + 1, 1);
  var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
  return days;
}
//获得本季度的开始月份
function getQuarterStartMonth() {
  var quarterStartMonth = 0;
  if (nowMonth < 3) {
    quarterStartMonth = 0;
  }
  if (2 < nowMonth && nowMonth < 6) {
    quarterStartMonth = 3;
  }
  if (5 < nowMonth && nowMonth < 9) {
    quarterStartMonth = 6;
  }
  if (nowMonth > 8) {
    quarterStartMonth = 9;
  }
  return quarterStartMonth;
}
//获得本周的开始日期
function getWeekStartDate() {
  var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek);
  return formatDate(weekStartDate);
}
//获得本周的结束日期
function getWeekEndDate() {
  var weekEndDate = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek));
  return formatDate(weekEndDate);
}
//获得上周的开始日期
function getLastWeekStartDate() {
  var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 7);
  return formatDate(weekStartDate);
}
//获得上周的结束日期
function getLastWeekEndDate() {
  var weekEndDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek - 1);
  return formatDate(weekEndDate);
}
//获得本月的开始日期
function getMonthStartDate() {
  var monthStartDate = new Date(nowYear, nowMonth, 1);
  return formatDate(monthStartDate);
}
//获得本月的结束日期
function getMonthEndDate() {
  var monthEndDate = new Date(nowYear, nowMonth, getMonthDays(nowMonth));
  return formatDate(monthEndDate);
}
//获得上月开始时间
function getLastMonthStartDate() {
  var lastMonthStartDate = new Date(nowYear, lastMonth, 1);
  return formatDate(lastMonthStartDate);
}
//获得上月结束时间
function getLastMonthEndDate() {
  var lastMonthEndDate = new Date(nowYear, lastMonth, getMonthDays(lastMonth));
  return formatDate(lastMonthEndDate);
}
//获得本季度的开始日期
function getQuarterStartDate() {
  var quarterStartDate = new Date(nowYear, getQuarterStartMonth(), 1);
  return formatDate(quarterStartDate);
}
//或的本季度的结束日期
function getQuarterEndDate() {
  var quarterEndMonth = getQuarterStartMonth() + 2;
  var quarterStartDate = new Date(nowYear, quarterEndMonth,
      getMonthDays(quarterEndMonth));
  return formatDate(quarterStartDate);
}

获得早上好、中午好、下午好、晚上好

/**
 * 获得早上好、中午好、下午好、晚上好
 * 用法:getTimeState()
 * @param str
 * @returns {string}
 */
function getTimeState() {
	// 获取当前时间
	let timeNow = new Date();
	// 获取当前小时
	let hours = timeNow.getHours();
	// 设置默认文字
	let text = ``;
	// 判断当前时间段
	if (hours >= 0 && hours <= 10) {
		text = `早上好`;
	} else if (hours > 10 && hours <= 14) {
		text = `中午好`;
	} else if (hours > 14 && hours <= 18) {
		text = `下午好`;
	} else if (hours > 18 && hours <= 24) {
		text = `晚上好`;
	}
	//console.log(`hours >>>>>`, hours);
	//console.log(`text >>>>`, text);
	// 返回当前时间段对应的状态
	return text;
};

其他函数

获得本页面地址栏参数

/**
 * 获得本页面地址栏参数
 * 用法:getUrlAddressParameter("name")
 * @param parameter
 * @returns {*}
 */
function getUrlAddressParameter(parameter){
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if(pair[0] == parameter){return pair[1];}
    }
    return null;
}

获得Guid

/**
 * 获得Guid
 * 用法:getGuid()
 * @returns {string}
 */
function getGuid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

根据json字段排序

/**
 * 根据json字段排序
 * 用法:var jsonStr = jsonStr.sort(up);
 * @param x
 * @param y
 * @returns {number}
 */
//按照升序排列
function up(x,y){
    return y.COUNT-x.COUNT
}

将JSON内部key值转换大小写和首字母大写

/**
 * @param {Object} json
 * @param {Object} type: 默认不传 ==>全部小写;传1 ==>全部大写;传2 ==>首字母大写
 * 将json的key值进行大小写转换
 */
function jsonKeysToCase(json,type){
	if(typeof json == 'object'){
		var tempJson = JSON.parse(JSON.stringify(json));
		toCase(tempJson);
		return tempJson;
	}else{
		return json;
	}
	
	function toCase(json){
		if(typeof json == 'object'){
			if(Array.isArray(json)){
				json.forEach(function(item){
					toCase(item);
				})
			}else{
				for (var key in json){
					var item = json[key];
					if(typeof item == 'object'){
						toCase(item);
					}
					delete(json[key]);
					switch (type){
						case 1:
							//key值全部大写
							json[key.toLocaleUpperCase()] = item;  
							break;
						case 2:
							//key值首字母大写,其余小写
							json[key.substring(0,1).toLocaleUpperCase() + key.substring(1).toLocaleLowerCase()] = item;  
							break;
						default:
							//默认key值全部小写
							json[key.toLocaleLowerCase()] = item;  
							break;
					}
				}
			}
		}
	}
}
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇