js实现两个日期的时间段,或距离当前时间的时间段,如:几秒前,几天前,几个月前

项目中需要显示在多久之前的更改记录,比如:3天前,2个月前。或者是工作的时间,比如:2010-06-01到2015-04-01是几年几个月。

下面是time.js文件的代码:

export default {
  //获取两个时间之间的时间段
  getTime: function(startTime, endTime) {
    let end
    if (endTime) {
      end = new Date(endTime)
    } else {
      end = new Date()
    }
    let endYear = end.getFullYear()
    let endMonth = end.getMonth() + 1
    let endDay = end.getDate()
    let endHour = end.getHours()
    let endMinute = end.getMinutes()
    let endSecond = end.getSeconds()

    let start = new Date(startTime)
      // 获取某一时间的年月日
    let startYear = start.getFullYear()
    let startMonth = start.getMonth() + 1
    let startDay = start.getDate()
    let startHour = start.getHours()
    let startMinute = start.getMinutes()
    let startSecond = start.getSeconds()

    let year, month, day, hour, minute, second

    //计算
    year = (endYear - startYear) > 0 ? (endYear - startYear) : 0

    if (endMonth > startMonth) {
      month = endMonth - startMonth
    } else if (endMonth == startMonth) {
      month = 0
    } else {
      if (year > 0) {
        year = year - 1
      }
      month = 12 - startMonth + endMonth
    }

    if (endDay > startDay) {
      day = endDay - startDay
    } else if (endDay == startDay) {
      day = 0
    } else {
      if (startMonth == 1 || startMonth == 3 || startMonth == 5 || startMonth == 7 || startMonth == 8 || startMonth == 10 || startMonth == 12) {
        day = 31 - startDay + endDay
      } else if (startMonth == 2) {
        //闰年 能被4整除 2月份是29天,不能就是28天
        if (startYear % 4 == 0 && startYear % 100 != 0 || startYear % 400 == 0) {
          day = 29 - startDay + endDay
        } else {
          day = 28 - startDay + endDay
        }
      } else {
        day = 30 - startDay + endDay
      }
      if (month > 0) {
        month = month - 1
      }
    }

    if (endHour > startHour) {
      hour = endHour - startHour
    } else if (endHour == startHour) {
      hour = 0
    } else {
      hour = 24 - startHour + endHour
      if (day > 0) {
        day = day - 1
      }
    }

    if (endMinute > startMinute) {
      minute = endMinute - startMinute
    } else if (endMinute == startMinute) {
      minute = 0
    } else {
      minute = 60 - startMinute + endMinute
      if (hour > 0) {
        hour = hour - 1
      }
    }

    if (endSecond > startSecond) {
      second = endSecond - startSecond
    } else if (endSecond == startSecond) {
      second = 0
    } else {
      second = 60 - startSecond + endSecond
      if (minute > 0) {
        minute = minute - 1
      }
    }

    return {
      year: year,
      month: month,
      day: day,
      hour: hour,
      minute: minute,
      second: second
    }
  }
}

调用方法:

import time from 'time.js';

time.getTime('2015-06-01 11:20:04', '2018-03-01 12:40:05');

返回结果:

{ //可根据需要显示月数或天数
    year: 3,
    month: 3,
    day: 0,
    hour: 1,
    minute: 20,
    second: 1
}

 

你可能感兴趣的:(javascript,vue)