這裏會擴展一些JS經常使用時間處理方法,內置時間對象的方法再也不贅述 —— 傳送門:http://www.w3school.com.cn/js/jsref_obj_date.aspthis
// 說明:JS時間Date格式化參數 // 參數:格式化字符串如:'yyyy-MM-dd hh:mm:ss' // 結果:如2016-06-01 10:09:00 Date.prototype.format = function (fmt) { var o = { "M+": this.getMonth() + 1, //月份 "d+": this.getDate(), //日 "h+": this.getHours(), //小時 "m+": this.getMinutes(), //分 "s+": this.getSeconds(), //秒 "q+": Math.floor((this.getMonth() + 3) / 3), // 季度 "S": this.getMilliseconds() // 毫秒 }; // 根據y的長度來截取年 if (/(y+)/.test(fmt)){ fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); } for (var 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; } // 用法: var time1 = new Date().format("yyyy-MM-dd"); var time2 = new Date(1469281964000).format("yyyy-MM-dd hh:mm:ss"); console.log(time1); console.log(time2);
// 參數:‘2019-03-05’ || 時間對象 // 結果:‘2019-03-04 至 2019-03-10’ function getWeekRange(date) { if(!date) return var now = new Date(date); var nowDayOfWeek = now.getDay(); // 星期日—>六(0->6) var nowDay = now.getDate(); var nowMonth = now.getMonth(); var nowYear = now.getYear(); // 2019年是119 nowYear += (nowYear < 2000) ? 1900 : 0; var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek+1); // 這周的週五 var weekEndDate = new Date(nowYear, nowMonth, nowDay + (7 - nowDayOfWeek)); // 7- 這周的週日 && 用5- 獲得這的週五 return weekStartDate.format('yyyy-MM-dd') + " 至 " + weekEndDate.format('yyyy-MM-dd'); } // 用法: getWeekRange(‘2019-03-05’) // ‘2019-03-04 至 2019-03-10’
//獲取當月第一天 function getFirstDayOfMonth () { var date = new Date(); date.setDate(1); return date.format('yyyy-MM-dd'); }
function getFirstDayOfMonth () { var date = new Date(); var month = date.getMonth(); date.setMonth(month+1); date.setDate(0); return date.format('yyyy-MM-dd'); }
function getFirstDayOfSeason () { var date = new Date(); var month = date.getMonth(); if(month <3 ){ date.setMonth(0); }else if(2 < month && month < 6){ date.setMonth(3); }else if(5 < month && month < 9){ date.setMonth(6); }else if(8 < month && month < 11){ date.setMonth(9); } date.setDate(1); return date.format('yyyy-MM-dd');; }
function getFirstDayOfYear () { var date = new Date(); date.setDate(1); date.setMonth(0); return date.format('yyyy-MM-dd');; }
Math.ceil(( new Date() - new Date(new Date().getFullYear().toString()))/(24*60*60*1000))+1;
function restDayOfYear() { var fullyear = new Date().getFullYear(); var nextyear = fullyear + 1; var lastday = new Date(new Date(nextyear,0,1) - 1); //本年的最後一毫秒: var now = new Date(); var diff = lastday - now; //毫秒數 return Math.ceil(diff / (1000 * 60 * 60 * 24)); }
getWeekZh(value) { var dateArray = value.split("-"); var zhWeek = "星期" + "日一二三四五六".charAt(new Date(dateArray[0], parseInt(dateArray[1] - 1), dateArray[2]).getDay()); return zhWeek }
未完待續...prototype