日期格式處理在前端的日常任務(wù)中非常常見应役,但是為此引入monent.js這樣的類庫又會顯得有點臃腫,畢竟我們一個特定的項目中燥筷,并不需要monent.js那么全的涵蓋范圍箩祥。另外,如果現(xiàn)在公司讓你自己手寫一個日歷組件(月歷肆氓、周歷)袍祖,日歷組件中需要耦合我們的其他業(yè)務(wù)需求,如果有一個任務(wù)列表,當(dāng)11月22號的待進(jìn)行任務(wù),我需要在日歷上有一個綠色圓點霞扬,表示當(dāng)天有待辦事項。下面介紹一些常規(guī)的函數(shù)寺滚,希望對大家有用。
- 月歷效果圖
函數(shù)目錄
- getFormatDateStr 獲得指定日期格式的字符串屈雄;
- getDayPrevAfter 獲得n天前/后的日期村视;
- formatDateWithTimeZone 格式化日期帶時區(qū),ISO 8601酒奶;
- countDownBySecond 倒計時蚁孔;
- monthSize 獲得指定日期所在月的天數(shù);
- getCalendarMonth 獲得指定日期所在月的第一周到第四/五周的數(shù)據(jù)組合惋嚎;
- getOneDateWeekIndex 獲得指定的某天所在該月的第幾周杠氢,下標(biāo)從0開始;
下面是詳細(xì)的說明:
- getFormatDateStr
/**
* [zeroPadding 小于10的數(shù)字補(bǔ)0另伍,必填]
* @param {[Int]} value [description]
* @return {[String]} [description]
*/
export function zeroPadding(value){
return value < 10 ? `0${value}` : value;
}
/**
* [_isDateStrSeparatorCh 判斷日期格式字符串的分隔符是否是中文]
* @param {[String]} str [必填]
* @return {[String]} [分隔符]
*/
function _getDateStrSeparator(str, startIndex, endIndex) {
startIndex = startIndex ? startIndex : 4;
endIndex = endIndex ? endIndex : 5;
let separator = str.slice(startIndex, endIndex);
if (separator === '年' || separator === '月' ) {
separator = 'Ch';
}
return separator;
}
/**
* [_isDateStrSeparatorCh 判斷日期格式字符串的分隔符是否是中文]
* @param {[String]} str [必填]
* @return {[String]} [分隔符]
*/
function _isDateStrSeparatorCh(str) {
if ( str.indexOf('年')!=-1 || str.indexOf('月')!=-1 ) {
return true;
}
return false;
}
/**
* [getFormatDateStr 獲得指定日期格式的字符串]
* @param {[String or Date]} date [要轉(zhuǎn)換的日期鼻百,必填]
* @param {[String]} dateFormatStr [要轉(zhuǎn)化的目標(biāo)格式,必填摆尝,2016-11-22之間的分隔符可任意温艇,可選項:
* 'yyyy-mm-dd hh:mm:ss','yyyy/mm/dd hh:mm:ss','yyyy.mm.dd hh:mm:ss','yyyy年mm月dd hh:mm:ss',
* 'yyyy-mm-dd hh:mm',
* 'mm-dd hh:mm',
* 'yyyy-mm-dd',
* 'mm-dd',
* 'hh:mm:ss',
* 'hh:mm'
* ]
* @return {[String]} [時間格式字符串]
*/
export function getFormatDateStr(date, dateFormatStr) {
if ( !(date instanceof Date) ) {
if ( date.indexOf('-') != -1 ) {
date.replace(/\-/g,'/');
}
date = new Date(date);
}
dateFormatStr = dateFormatStr.toLowerCase();
if (!dateFormatStr){
return false;
}
let returnStr = '',
separator = _getDateStrSeparator(dateFormatStr),
year = date.getFullYear(),
month = date.getMonth() + 1,
day = date.getDate(),
hour = date.getHours(),
minute = date.getMinutes(),
second = date.getSeconds();
if ( /^yyyy(.{1})mm(.{1})dd hh:mm:ss$/.test(dateFormatStr) ) {
if (_isDateStrSeparatorCh(dateFormatStr)) {
returnStr = `${year}年${zeroPadding(month)}月${zeroPadding(day)}日`;
} else {
separator =
returnStr = `${year}${separator}${zeroPadding(month)}${separator}${zeroPadding(day)}`;
}
returnStr += ` ${zeroPadding(hour)}:${zeroPadding(minute)}:${zeroPadding(second)}`;
} else if ( /^yyyy(.{1})mm(.{1})dd hh:mm$/.test(dateFormatStr) ) {
if (_isDateStrSeparatorCh(dateFormatStr)) {
returnStr = `${year}年${zeroPadding(month)}月${zeroPadding(day)}日`;
} else {
returnStr = `${year}${separator}${zeroPadding(month)}${separator}${zeroPadding(day)}`;
}
returnStr += ` ${zeroPadding(hour)}:${zeroPadding(minute)}`;
} else if ( /^mm(.{1})dd hh:mm$/.test(dateFormatStr) ) {
if (_isDateStrSeparatorCh(dateFormatStr)) {
returnStr = `${zeroPadding(month)}月${zeroPadding(day)}日`;
} else {
separator = _getDateStrSeparator(dateFormatStr, 2, 3);
returnStr = `${zeroPadding(month)}${separator}${zeroPadding(day)}`;
}
returnStr += ` ${zeroPadding(hour)}:${zeroPadding(minute)}`;
} else if ( /^yyyy(.{1})mm(.{1})dd$/.test(dateFormatStr) ) {
if (_isDateStrSeparatorCh(dateFormatStr)) {
returnStr = `${year}年${zeroPadding(month)}月${zeroPadding(day)}日`;
} else {
returnStr = `${year}${separator}${zeroPadding(month)}${separator}${zeroPadding(day)}`;
}
} else if ( /^mm(.{1})dd$/.test(dateFormatStr) ) {
if (_isDateStrSeparatorCh(dateFormatStr)) {
returnStr = `${zeroPadding(month)}月${zeroPadding(day)}日`;
} else {
separator = _getDateStrSeparator(dateFormatStr, 2, 3);
returnStr = `${zeroPadding(month)}${separator}${zeroPadding(day)}`;
}
} else if ( /^hh:mm:ss$/.test(dateFormatStr) ) {
returnStr = `${zeroPadding(hour)}:${zeroPadding(minute)}:${zeroPadding(second)}`;
} else if ( /^hh:mm$/.test(dateFormatStr) ) {
returnStr = `${zeroPadding(hour)}:${zeroPadding(minute)}`;
}
return returnStr;
}
- getDayPrevAfter
/**
* [getDayPrevAfter 獲得n天前/后的日期]
* @param {[String]} date [日期,非必填參數(shù)堕汞,表示調(diào)用時的時間]
* @param {[String]} type [前一天還是后一天勺爱,非必填參數(shù),默認(rèn)后一天]
* @param {[Int]} daysNum [天數(shù)讯检,非必填參數(shù)琐鲁,默認(rèn)一天]
* @return {[Date]} [description]
*/
export function getDayPrevAfter(date, type, daysNum) {
date = date ? date : new Date();
type = type ? type : 'after';
daysNum = daysNum ? daysNum : 1;
if ( !(date instanceof Date) ) {
if ( date.indexOf('-') != -1 ) {
date.replace(/\-/g,'/');
}
date = new Date(date);
}
let returnDate = date;
if (type === 'prev') {
returnDate = new Date(date.getTime() - (daysNum * 24 * 60 * 60 * 1000));
} else if (type === 'after') {
returnDate = new Date(date.getTime() + (daysNum * 24 * 60 * 60 * 1000));
}
return returnDate;
}
- formatDateWithTimeZone
/**
* [formatDateWithTimeZone 格式化日期帶時區(qū),ISO 8601]
* @param {[Date]} date [日期人灼,非必填參數(shù)绣否,表示調(diào)用時的時間]
* @return {[String]} [ISO 8601格式的日期,example: 2016-11-21T14:09:15+08:00]
*/
export function formatDateWithTimeZone(date) {
date = date ? date : new Date();
if ( !(date instanceof Date) ) {
if ( date.indexOf('-') != -1 ) {
date.replace(/\-/g,'/');
}
date = new Date(date);
}
let tzo = -date.getTimezoneOffset(),
dif = tzo >= 0 ? '+' : '-',
pad = function (num) {
let norm = Math.abs(Math.floor(num));
return zeroPadding(norm);
};
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}${dif}${pad(tzo / 60)}:${pad(tzo % 60)}`;
}
- countDownBySecond
/**
* [countDownBySecond 倒計時]
* @param {[Int]} restSeconds [剩余秒數(shù)挡毅,必填]
* @param {[Int]} timeInterval [時間間隔蒜撮,非必填,默認(rèn)1000ms]
* @param {[Function]} func [每倒計時一次跪呈,就需要執(zhí)行一次的回調(diào)函數(shù)名段磨,非必填]
* @param {[Function]} endFun [倒計時結(jié)束需要執(zhí)行的函數(shù)名,非必填]
* @return {[null]} [無返回值]
*/
export function countDownBySecond(restSeconds, timeInterval, func, endCallback) {
let timer = null;
let total = restSeconds;
timeInterval = timeInterval ? timeInterval : 1000;
timer = setInterval(function() {
--total;
if (total <= 0) {
clearInterval(timer);
endCallback && endCallback();
}
func && func(total);
}, timeInterval);
}
- monthSize
/**
* [monthSize 獲得指定日期所在月的天數(shù)]
* @param {[Date]} oDate [指定的日期耗绿,非必填苹支,默認(rèn)為當(dāng)天]
* @return {[Int]} [總天數(shù)]
*/
function monthSize(oDate) {
oDate = oDate ? oDate : new Date();
let year = oDate.getFullYear(),
month = oDate.getMonth(),
_oDate = new Date();
_oDate.setFullYear(year);
_oDate.setMonth(month + 1, 0);
return _oDate.getDate();
}
- getCalendarMonth
/**
* [getCalendarMonth 獲得指定日期所在月的第一周到第四/五周的數(shù)據(jù)組合,形如:
* [{
"date": "2016/10/30", //日期字符串
"dateNum": 30, //日
"isCurMonth": false, //是否當(dāng)前月
"weekIndex": 0 //是本月的第幾周误阻,下標(biāo)從0開始
},{
"date": "2016/10/31",
"dateNum": 31,
"isCurMonth": false,
"weekIndex": 0
},{
"date": "2016/11/1",
"dateNum": 1,
"day": 2,
"isCurMonth": true,
"isToday": false,
"weekIndex": 0
}]
]
* @param {[Date]} param [指定的日期债蜜,非必填晴埂,默認(rèn)為當(dāng)天]
* @return {[Array]} [獲得指定日期所在月的第一周到第四/五周的數(shù)據(jù)組合]
*/
export function getCalendarMonth(date) {
date = date ? date : new Date();
let y = date.getFullYear();
let m = date.getMonth();
let _m;
let firstDay = new Date(y, m, 1).getDay(); //當(dāng)月第一天 周期
let days = monthSize(date);//當(dāng)月天數(shù)
let prevMonthDays = monthSize(new Date(y, m - 1));//上月天數(shù)
let initPrevDay = prevMonthDays - firstDay;
let lines = Math.ceil((firstDay + days) / 7);
_m = new Array(lines * 7);
let nextMonthDay = 0;
for (let i = 0; i < _m.length; i++) {
let weekIndex = parseInt(i / 7);
if (i < firstDay) {
let date = ++initPrevDay;
if (m === 0 && date > 7) {
_m[i] = {
isCurMonth: false,
dateNum: date,
weekIndex,
date: `${y - 1}/${12}/${date}`
};
} else {
_m[i] = {
isCurMonth: false,
dateNum: date,
weekIndex,
date: `${y}/${m}/${date}`
};
}
} else if (i >= (firstDay + days)) {
let date = ++nextMonthDay;
if (m === 11 && date <= 7) {
_m[i] = {
isCurMonth: false,
dateNum: date,
weekIndex,
date: `${y + 1}/${1}/${date}`
};
} else {
_m[i] = {
isCurMonth: false,
dateNum: date,
weekIndex,
date: `${y}/${m + 2}/${date}`
};
}
} else {
let _date = i - firstDay + 1;
let today = new Date();
let today_y = today.getFullYear();
let today_m = today.getMonth();
let today_d = today.getDate();
let isToday = today_y === y && today_m === m && today_d === _date ? true : false;
_m[i] = {
dateNum: _date, //日期
day: i % 7, //周期
weekIndex,
isCurMonth: true,
isToday,
date: `${y}/${m + 1}/${_date}`
};
}
}
return _m;
}
- getOneDateWeekIndex
/**
* [getOneDateWeekIndex 獲得指定的某天所在該月的第幾周,下標(biāo)從0開始]
* @param {[Date]} date [指定的日期寻定,非必填儒洛,默認(rèn)為當(dāng)天]
* @return {[Int]} [在該月的第幾周]
*/
export function getOneDateWeekIndex(date) {
date = date ? date : new Date();
let monthDays = getCalendarMonth(date);
let dateString = getFormatDateStr(date, '/', true, false, false);
let returnDate = monthDays.filter(item => {
return item.date === dateString;
});
let weekIndex = returnDate[0].weekIndex;
return weekIndex ? weekIndex : 0;
}