javascript兼容IE的昨天,今天,本周,本月,上月

今天测试发现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
  }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值