Record the time-related functions in JS, taking today as an example2022-09-14 11:56:47星期三
new Date().getYear(); // 122 , IE浏览器为2022 获取年份
new Date().getFullYear() // 2022 获取当前年份(1970~)
new Date().getMonth() // 8 获取当前月份-1(0-11)
new Date().getDate() // 14 获取当前日数 (1-31)
new Date().getDay() // 3 获取当前星期几(0-6)
new Date().getTime() // 1663127701925 获取从1970.1.1到当前时间毫秒数
new Date().getHours() // 11 获取当前小时(0-23)
new Date().getMinutes() // 56 获取当前分钟数(0-59)
new Date().getSeconds() // 47 获取当前秒数 (0-59)
new Date().getMilliseconds() // 856 获取当前毫秒数(0-999)
new Date().toLocaleString() // 2022/9/14 11:56:47 获取当前日期和时间
new Date().toLocaleDateString() // 2022/9/14 获取当前日期
new Date().toLocaleTimeString() // 11:56:47 获取当前时间
important point
The getYear() function is the current year 2022-1900=122. In IE, when today’s year is greater than or equal to 2000, add 1900 directly, so it will display 122+1900=2022 in IE- toLocaleString(), toLocaleDateString(), toLocaleTimeString() may have compatibility issues
Among the built-in functions, the following are supplements, which can be added according to their own development needs
/*
日期格式化 (yyyy-mm-dd HH:MM:SS 星期X)
myFormat() // 2022-09-14 11:56:47 星期三
*/
function myFormat() {
var tDate = new Date();
var week = ['日','一','二','三','四','五','六'];
var str = tDate.getFullYear() + '-' + String(Number(tDate.getMonth()) + 1).toString().padStart(2, '0') + '-' + tDate.getDate().toString().padStart(2, '0') + ' ' + tDate.getHours() + ':' + tDate.getMinutes() + ':' + tDate.getSeconds() + ' 星期' + week[tDate.getDay()];
return str;
}
/*
日期天数作差
daysBetween('2022-09-14','2022-09-16') // 2
*/
function daysBetween(str1, str2) {
var m1 = str1.substring(5, str1.lastIndexOf('-'))
var d1 = str1.substring(str1.length, str1.lastIndexOf('-') + 1)
var y1 = str1.substring(0, str1.indexOf('-'))
var m2 = str2.substring(5, str2.lastIndexOf('-'))
var d2 = str2.substring(str2.length, str2.lastIndexOf('-') + 1)
var y2 = str2.substring(0, str2.indexOf('-'))
var cha = ((Date.parse(m1 + '/' + d1 + '/' + y1) - Date.parse(m2 + '/' + d2 + '/' + y2)) / 86400000)
return Math.abs(cha)
}
/* 获取当前时间这一周的周日和周六 如9月14日
周日:getWeekDay(new Date(), true) //2022-09-11
周六:getWeekDay(new Date(), false) //2022-09-17
*/
function getWeekDay(data, isFirst) {
var today = new Date(data)
var td = today.getDay()
var interval
if (isFirst) {
if (td == 0) return data
interval = td - 0
today.setDate(today.getDate() - interval)
} else {
if (td == 6) return data
interval = 6 - td
today.setDate(today.getDate() + interval)
}
return today.getFullYear() + '-' + (today.getMonth() + 1).toString().padStart(2, '0') + '-' + today.getDate().toString().padStart(2, '0')
}