一、日期时间
1.获取当前日期
function getCurrentDate() {
var currentDateTime = new Date();
var year = currentDateTime.getFullYear();
var month = ('0' + (currentDateTime.getMonth() + 1)).slice(-2);
var day = ('0' + currentDateTime.getDate()).slice(-2);
var formattedDate = year + '-' + month + '-' + day;
return formattedDate;
}
2.获取当前日期时间
代码如下:
function getCurrentDateTime() {
var currentDateTime = new Date();
var year = currentDateTime.getFullYear();
var month = ('0' + (currentDateTime.getMonth() + 1)).slice(-2);
var day = ('0' + currentDateTime.getDate()).slice(-2);
var hour = ('0' + currentDateTime.getHours()).slice(-2);
var minute = ('0' + currentDateTime.getMinutes()).slice(-2);
var second = ('0' + currentDateTime.getSeconds()).slice(-2);
var formattedDateTime = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
return formattedDateTime;
}
3.格式化日期
代码如下:
function formatDate(date) {
var year = date.getFullYear();
var month = ('0' + (date.getMonth() + 1)).slice(-2);
var day = ('0' + date.getDate()).slice(-2);
return year + '-' + month + '-' + day;
}
4.格式化日期时间
代码如下:
function formatDateTime(date) {
var year = date.getFullYear();
var month = ('0' + (date.getMonth() + 1)).slice(-2);
var day = ('0' + date.getDate()).slice(-2);
var hour = ('0' + date.getHours()).slice(-2);
var minute = ('0' + date.getMinutes()).slice(-2);
var second = ('0' + date.getSeconds()).slice(-2);
return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
}
5.将日期时间格式化为数字
代码如下:
function dateTimeToNumber(dateTime) {
var dateParts = dateTime.split(" ")[0].split("-");
var timeParts = dateTime.split(" ")[1].split(":");
var year = parseInt(dateParts[0]);
var month = parseInt(dateParts[1]);
var day = parseInt(dateParts[2]);
var hours = parseInt(timeParts[0]);
var minutes = parseInt(timeParts[1]);
var seconds = parseInt(timeParts[2]);
var number = Date.UTC(year, month - 1, day, hours, minutes, seconds);
return number;
}
6.根据当前日期和自然天数计算结束日期
代码如下:
function calculateEndDate(currentDate, numDays) {
var endDate = new Date(currentDate);
endDate.setDate(endDate.getDate() + numDays);
return endDate;
}
二、防抖节流
1.防抖
代码如下:
function debounce(func, delay) {
var timer = null;
return function () {
clearTimeout(timer);
timer = setTimeout(function () {
func.apply(this, arguments);
}, delay);
};
}
2.节流
代码如下:
function throttle(func, delay) {
var timer = null;
return function () {
if (!timer) {
timer = setTimeout(function () {
func.apply(this, arguments);
timer = null;
}, delay);
}
};
}