今天测试发现IE不支持new Date()里面的参数带有时分秒。导致时间显示不出来,类似"2018-07-24 12:05:12",但据说支持"2018/07/24 12:05:12"。试过很多种方法,最终解决:
// 获取昨天的开始时间
export function getYesterdayStart() {
const now = new Date()
now.setTime(now.getTime() - 24 * 60 * 60 * 1000)
return now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate() + ' 00:00:00'
}
// 获取昨天的结束时间
export function getYesterdayEnd() {
const now = new Date()
now.setTime(now.getTime() - 24 * 60 * 60 * 1000)
return now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate() + ' 23:59:59'
}
// 获取今天的开始时间
export function getTodayStart() {
const now = new Date()
return now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate() + ' 00:00:00'
}
// 获得本周的开始日期(00:00:00)
export function getWeekStartTime() {
const now = new Date()
const nowDayOfWeek = now.getDay()
now.setDate(now.getDate() - (nowDayOfWeek - 1))
return now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate() + ' 00:00:00'
}
// 获得本月第1天的开始时间(00:00:00)
export function getMonthStartTime() {
return new Date(new Date().getFullYear(), new Date().getMonth(), 1)
}
// 获得上月第1天的开始时间(00:00:00)
export function getLastMonthStartTime() {
return new Date(new Date().getFullYear(), new Date().getMonth() - 1, 1)
}
// 获得上月最后1天的时间(23:59:59)
export function getLastMonthEndTime() {
return new Date(new Date(new Date().getFullYear(), new Date().getMonth(), 1) - 1)
以上有的返回字符串。有的返回Date()。当返回Date()时,和vue.js的时间插件配合传值到后台需要将UTC时间格式化为字符串。不然无法处理。转换方法:
// UTC时间转yyyy-MM-dd HH:mm:ss
export function formatUTCTime(UTCDateString) {
if(!UTCDateString){
return '-'
}
function formatFunc(str) { //格式化显示
return str > 9 ? str : '0' + str
}
let date2 = new Date(UTCDateString) //这步是关键
let year = date2.getFullYear()
let mon = formatFunc(date2.getMonth() + 1)
let day = formatFunc(date2.getDate())
let hour = formatFunc(date2.getHours())
let min = formatFunc(date2.getMinutes())
let second = formatFunc(date2.getSeconds())
return year+'-'+mon+'-'+day+' '+hour+':'+min +':'+second
}