new Date() 日期对象
let currentime = new Date() // 返回中国标准时间
let year = currentime.getFullYear() // 返回年 2022
let month = currentime.getMonth() + 1 // 返回月 6
let day = currentime.getDate() // 返回日 21
以下封装用到的补0
// 一位数前补0
const correction = (time)=>{
return time>=0 && time<10 ? '0'+time :time
}
获取今天的时间
export const getTodayTime =()=>{
let currentime = new Date()
let year = currentime.getFullYear()
let month = currentime.getMonth() + 1
let day = currentime.getDate()
return correction(year) + '-' + correction(month) + '-' + correction(day)
}
获取最近7天的时间
// 获取最近7天的时间
export const getSevenDays =()=>{
let time = {
one : getOneDay(0),
two : getOneDay(-1),
three : getOneDay(-2),
four : getOneDay(-3),
five : getOneDay(-4),
six : getOneDay(-5),
seven : getOneDay(-6),
}
return time
}
// 测试获取最近7天的日期
const getOneDay = (day)=>{
let today = new Date()
let targetday_milliseconds=today.getTime() + 1000*60*60*24*day
today.setTime(targetday_milliseconds)
let tYear = today.getFullYear()
let tMonth = today.getMonth()
let tDate = today.getDate()
tMonth = correction(tMonth + 1)
tDate = correction(tDate)
return tYear+"-"+tMonth+"-"+tDate
}
获取当前月份的所有日期
export const getMonthDays =()=>{
let year = new Date().getFullYear()
let month = new Date().getMonth() + 1
let day = new Date(year, month, 0).getDate()
let current_month_num = day
let current_month = []
for(let i = 1;i <= current_month_num;i++){
let cday = month + '-' + i
current_month.push(cday)
}
return current_month
}
获取今天和昨天的时间
// 获取今天和昨天的时间
export const getTodayYesTime =()=>{
let currentime = new Date()
let year = currentime.getFullYear()
let month = currentime.getMonth() + 1
let day = currentime.getDate()
// console.log(year,month,day)
let yesterday = new Date(today)
let yesyear = yesterday.getFullYear()
let yesmonth = yesterday.getMonth() + 1
let yesday = yesterday.getDate()
let time = {
today : correction(year) + '-' + correction(month) + '-' + correction(day),
yesterday : correction(yesyear) + '-' + correction(yesmonth) + '-' + correction(yesday)
}
return time
}
// 获取上个月最后一天的日期
// 获取上个月最后一天的日期
export const lastMonth =()=>{
let date = new Date()
let year = date.getFullYear()
let mon = date.getMonth()
if(mon == 0){
mon = 12
year = year - 1
}
let lastDay = new Date(year, mon, 0).getDate()
return year + "-" + correction(mon) + "-" +lastDay
}
// 获取当前时间是本年的第几周
getWeek(val){
console.log(val)
let firstDay = new Date(val.getFullYear(), 0, 1) // 当前年份的第一天
let dayOfWeek = firstDay.getDay() // 当前年份的第一天是周几
let spendDay = 1
if(dayOfWeek !=0){
spendDay = 7 -dayOfWeek + 1 // 距离下周还有几天
}
firstDay = new Date(val.getFullYear(), 0, 1 + spendDay) //今年的第一周的第一天的日期
let d = Math.ceil((val.valueOf() - firstDay.valueOf()) / 86400000) // 计算相差几天
let result = Math.ceil(d / 7)
let year = val.getFullYear()
let week = result
if(dayOfWeek !== 0){
week = result + 1
}
if(week === 53 && val.getDate() !== 26){
week = 1
year += 1
}
return `${year}年第${week}周`
}