获取最近七天(含今天)
const lastSevenDays = () => {
const days = []
for (let i = 6; i >= 0; i--) {
const day = new Date()
day.setDate(day.getDate() - i)
const month = day.getMonth() + 1
const date = day.getDate()
const formattedDate = month + '月' + date + '日'
days.push(formattedDate)
}
return days
}
获取当前时间 时/分/秒
import { useEffect, useState } from 'react'
function useCurrentTime() {
const [currentTime, setCurrentTime] = useState(new Date())
useEffect(() => {
const intervalId = setInterval(() => {
setCurrentTime(new Date())
}, 1000)
return () => {
clearInterval(intervalId)
}
}, [])
const formattedTime = `${currentTime.getHours().toString().padStart(2, '0')}:${currentTime.getMinutes().toString().padStart(2, '0')}:${currentTime.getSeconds().toString().padStart(2, '0')}`
当前星期
import { useState, useEffect } from 'react'
function useDayOfWeek() {
const [dayOfWeek, setDayOfWeek] = useState('')
useEffect(() => {
const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
const now = new Date()
const currentDayOfWeek = weekdays[now.getDay()]
setDayOfWeek(currentDayOfWeek)
// 可以把定时器去掉
const intervalId = setInterval(() => {
const newNow = new Date()
const newDayOfWeek = weekdays[newNow.getDay()]
setDayOfWeek(newDayOfWeek)
}, 60 * 1000) // 每分钟更新一次
return () => clearInterval(intervalId)
}, [])
return dayOfWeek
}
当前日期
import { useState, useEffect } from 'react'
function useFormattedDate() {
const [formattedDate, setFormattedDate] = useState('')
useEffect(() => {
const formatDate = date => {
const year = date.getFullYear()
const month = ('0' + (date.getMonth() + 1)).slice(-2)
const day = ('0' + date.getDate()).slice(-2)
return `${year}/${month}/${day}`
}
const now = new Date()
const currentFormattedDate = formatDate(now)
setFormattedDate(currentFormattedDate)
}, [])
return formattedDate
}