目录
utc 时间转北京时间
function utc2beijing (utc_datetime) {
let T_pos = utc_datetime.indexOf('T')
let Z_pos = utc_datetime.indexOf('Z')
let year_month_day = utc_datetime.substr(0, T_pos)
let hour_minute_second = utc_datetime.substr(T_pos + 1, Z_pos - T_pos - 1)
let new_datetime = year_month_day + ' ' + hour_minute_second
timestamp = new Date(Date.parse(new_datetime))
timestamp = timestamp.getTime()
timestamp = timestamp / 1000
var timestamp = timestamp + 8 * 60 * 60
let time = new Date(parseInt(timestamp) * 1000)
let year = time.getFullYear()
let month = ('0' + (time.getMonth() + 1)).slice(-2)
let day = ('0' + time.getDate()).slice(-2)
let beijing_datetime = year + '-' + month + '-' + day
return beijing_datetime
}
调用
const ToBeijing = (utcTime) => {
const utcDate = new Date(utcTime).toISOString()
return utc2beijing(utcDate)
}
ToBeijing(new Date()) // '2023-12-21'
当前月加n
const getMonth = (utcTime, months) => {
let dateTime:any = new Date()
dateTime.setDate(1)
dateTime = dateTime.setMonth(new Date(utcTime).getMonth() + months)
dateTime = new Date(dateTime)
const utcDate = dateTime.toISOString()
return utc2beijing(utcDate)
}
getMonth(new Date(), 1) // 当前月加一
两个时间之间总天数
const getDiffDay = (date_1, date_2) => {
let totalDays, diffDate
let myDate_1 = Date.parse(date_1)
let myDate_2 = Date.parse(date_2)
diffDate = Math.abs(myDate_1 - myDate_2)
totalDays = Math.floor(diffDate / (1000 * 3600 * 24))
return totalDays
}
getDiffDay('2023-11-01', '2023-12-01') // 30
const getDaysBetween = (startDate, enDate) => {
const sDate = Date.parse(startDate)
const eDate = Date.parse(enDate)
if (sDate > eDate) {
return 0
}
if (sDate === eDate) {
return 1
}
const days = (eDate - sDate) / (1 * 24 * 60 * 60 * 1000)
return days
}
getDaysBetween('2023-11-01', '2023-12-01') // 30
当前月总天数
const getMonthDays = (target) => {
let year = target.split('-')[0]
let month = target.split('-')[1]
let date = new Date(year, month, 0)
return date.getDate()
}
getMonthDays('2023-11-21') // 30