最近的小程序项目中涉及到了年假规划,对日期、时间的处理函数用的比较多,在此做一下简单总结。
0 获取当前年-月-日
function getNowDate ( ) {
let now = new Date ( ) ;
let year = now. getFullYear ( ) ;
let month = now. getMonth ( ) + 1 ;
let date = now. getDate ( ) ;
return year + "-" + month + "-" + date;
}
1 获取当前年-月-日 时:分:秒
function getNowDateTime ( ) {
let date = new Date ( ) ;
let seperator1 = "-" ;
let seperator2 = ":" ;
let month = date. getMonth ( ) + 1 ;
let strDate = date. getDate ( ) ;
let strHours = date. getHours ( ) ;
let strMinutes = date. getMinutes ( ) ;
let strSeconds = date. getSeconds ( ) ;
if ( month >= 1 && month <= 9 ) {
month = "0" + month;
}
if ( strDate >= 0 && strDate <= 9 ) {
strDate = "0" + strDate;
}
if ( strHours >= 0 && strHours <= 9 ) {
strHours = "0" + strHours;
}
if ( strMinutes >= 0 && strMinutes <= 9 ) {
strMinutes = "0" + strMinutes;
}
if ( strSeconds >= 0 && strSeconds <= 9 ) {
strSeconds = "0" + strSeconds;
}
let currentdate = date. getFullYear ( ) + seperator1 + month + seperator1 + strDate + " " + strHours + seperator2 + strMinutes + seperator2 + strSeconds;
return currentdate;
}
2 判断两个时间段是否交叉
实现思路:第二个时间段的开始时间晚于第一个日期的结束时间即可
function isCross ( endTime1, beginTime2) {
let beginTime2Int = new Date ( beginTime2) . getTime ( ) ;
let endTime1Int = new Date ( endTime1) . getTime ( ) ;
if ( beginTime2Int <= endTime1Int) {
return true ;
} else {
return false ;
}
}
3 判断选择的日期是否在今天之前
实现思路:分别将当前日期和要比较的日期getTime(),然后比较即可
function isBeforToday ( selectedTime) {
let date = new Date ( ) ;
if ( new Date ( selectedTime) . getTime ( ) < new Date ( date) . getTime ( ) ) {
return true ;
} else {
return false ;
}
}
另外,因为不能今天休年假今天才申请,所以之后修改了判断方式,多了一个等号
function isBeforToday ( selectedTime) {
let date = new Date ( ) ;
if ( new Date ( selectedTime) . getTime ( ) <= new Date ( date) . getTime ( ) ) {
return true ;
} else {
return false ;
}
}
4 计算日期间隔
function getDateInterval ( begin, end) {
return ( new Date ( end) . getTime ( ) - new Date ( begin) . getTime ( ) ) / ( 24 * 60 * 60 * 1000 ) + 1 ;
}