js日期的处理

147 阅读1分钟

日期常用获取方法

  • new Date()                获取当前时间

  • getDate()                  以数值返回天(1-31)

  • getDay()                   以数值获取周名(0-6)// 0 是星期日

  • getFullYear()            获取四位的年(yyyy)

  • getHours()               获取小时(0-23)

  • getMilliseconds()    获取毫秒(0-999)

  • getMinutes()           获取分(0-59)

  • getMonth()             获取月(0-11) // 执行后+1就是当前月份

  • getSeconds()          获取秒(0-59)

  • getTime()                获取时间戳(从 1970 年 1 月 1 日至今)

计算日期差方法

function datedifference(sDate1, sDate2) {      //sDate1sDate2是2006-12-18格式      var dateSpan, iDays      sDate1 = Date.parse(sDate1)      sDate2 = Date.parse(sDate2)      dateSpan = sDate2 - sDate1      dateSpan = Math.abs(dateSpan)      iDays = Math.floor(dateSpan / (24 * 3600 * 1000))      iDays = iDays + 1      return iDays}

日期比较大小

function compare(date1, date2) {      var oDate1 = new Date(date1)      var oDate2 = new Date(date2)      if (oDate1.getTime() > oDate2.getTime()) {        console.log('第一个大')      } else {        console.log('第二个大')      }}
compare('2015-10-10 12:12:00','2015-10-11 13:10:36');

根据日期和天数计算日期(含当天)

calculate(a,b){      let date1 = new Date(a).getTime() //获取a时间戳 a = 'yyyy-MM-dd'      let date2 = (b-1)*86400000 //获取b时间戳  b=天数      let date = new Date(date1+date2) //获取a+b日期      let yyyy = date.getFullYear() //获取新日期年份      let HH = date.getMonth()+1<10?'0'+(date.getMonth()+1):date.getMonth()+1 //获取新日期月份,不足100      let dd = date.getDate()<10?'0'+date.getDate():date.getDate() //获取新日期号数 不足100      Vue.set(this.placeForm,'outTime',yyyy+'-'+HH+'-'+dd) //给离境日期赋值},