最近的一个项目需要写一个日历插件,对一些知识点有了新认识,所以记下方便以后的查阅
其中对日期函数有了更深入的了解:
var date = new Date();
date .getYear(); //获取当前年份(2位)
date .getFullYear(); //获取完整的年份(4位,1970-????)
date .getMonth(); //获取当前月份(0-11,0代表1月)
date .getDate(); //获取当前日(1-31)
date .getDay(); //获取当前星期X(0-6,0代表星期天)
date .getTime(); //获取当前时间(从1970.1.1开始的毫秒数)
date .getHours(); //获取当前小时数(0-23)
date .getMinutes(); //获取当前分钟数(0-59)
date .getSeconds(); //获取当前秒数(0-59)
date .getMilliseconds(); //获取当前毫秒数(0-999)
date .toLocaleDateString(); //获取当前日期
var mytime=date .toLocaleTimeString(); //获取当前时间
date .toLocaleString( ); //获取日期与时间
下面的具体的代码:
<table class="bgtable">
<thead>
<tr>
<!--汉字表头-->
<th v-for="(item,index) in daynamearr" :key="index">{{item}}</th>
</tr>
</thead>
<tbody>
<tr v-for="(week, index) in theweek()" :key="index">
<td v-for="(item, index) in week" :key="index" :class="{'gray': item.prevmonth || item.nextmonth}" @click="viewAttendance(item.day)">
<div class="dot" :class="[item.correct == '正常' ? 'success' : (item.correct == '异常' ? 'warning' : (item.correct == '无' ? 'kong' : 'rest'))]">{{item.typesetting}}
</div>
</tr>
</tbody>
</table>
data() {
return {
daynamearr: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"], //本月的本期构成
dayarr: [],
arr: [],
}
}
getCalendar(year, month, isClear) {
if (isClear) {
this.dayarr = [];
}
var themonth1stday = new Date(year, month - 1, 1).getDay();
var y = month == 12 ? year + 1 : year;
var m = month == 12 ? 1 : month;
var themonthdaysamount = new Date(new Date(y, m, 1) - 1).getDate();
var prevmonthlastday = new Date(
new Date(year, month - 1, 1) - 1
).getDate();
while (themonth1stday-- > 0) {
this.dayarr.unshift({
day: prevmonthlastday--,
prevmonth: true,
currentmonth: false
});
} //本月的日期
var count = 0;
while (themonthdaysamount--) {
this.dayarr.push({
day: ++count,
currentmonth: true
});
}
var c = 42 - this.dayarr.length;
var count2 = 1;
while (c-- > 0) {
this.dayarr.push({
day: count2++,
nextmonth: true,
currentmonth: false
});
}
var _arr = [];
for (var i = 0; i < 6; i++) {
var _week = [];
for (var j = 0; j < 7; j++) {
_week.push(this.dayarr[i * 7 + j]);
}
_arr.push(_week);
}
this.arr = _arr
},
项目中还有一些其他小功能:计算上班的时间
getWorkTime(time1, time2) {
let dateDiff = time1 - time2;
let dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000));
let leave1 = dateDiff % (24 * 3600 * 1000);
let hours = Math.floor(leave1 / (3600 * 1000));
let leave2 = leave1 % (3600 * 1000);
let minutes = Math.floor(leave2 / (60 * 1000));
let leave3 = leave2 % (60 * 1000);
let seconds = Math.round(leave3 / 1000);
return hours + "小时" + minutes + "分钟";
},
点击获取日期和星期
getCurrentWeek(w) {
let date = new Date();
if(w == undefined) {
w =date.getDay();
}
switch(w) {
case 0: {
this.currentWeek = "星期日";
} break;
case 1: {
this.currentWeek = "星期一";
} break;
case 2: {
this.currentWeek = "星期二";
} break;
case 3: {
this.currentWeek = "星期三";
} break;
case 4: {
this.currentWeek = "星期四";
} break;
case 5: {
this.currentWeek = "星期五";
} break;
case 6: {
this.currentWeek = "星期六";
} break;
}
},