vue全局函数-日期处理(时间格式化,获取月初,月末,几天前,时间戳转时间)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/gongpan2468/article/details/85782304

在src目录新建common目录,该目录下存放一些公共的js,比如过滤器,全局变量,全局函数(包括store)等

baseFuns.js

exports.install = function (Vue, options) {

    // 时间格式化
    Vue.prototype.format_date = function (DateFor){//全局函数1
      let year = DateFor.getFullYear()
      let month = DateFor.getMonth() + 1
      let day = DateFor.getDate()
      if (month >= 1 && month <= 9) {
          month = "0" + month;
      }
      if (day >= 0 && day <= 9) {
          day = "0" + day;
      }
      let tmp= year + '-' + month + '-' + day
      return tmp
    };

    // 获取月初,获取 当前月+gap 的月初(若gap为-1,则获取上月初,若gap为1,则获取下月初,
    Vue.prototype.get_month_first = function (gap){
      let date1 = new Date();
      // 获取间隔月
      let gapMonth = date1.getMonth() + gap
      // 获取间隔月月初
      let gapMonthFirstDay=new Date(date1.getFullYear(),gapMonth,1);
      let firstDay = this.format_date(gapMonthFirstDay)
      console.log(firstDay)
      return firstDay
    };

    // 获取月末
    Vue.prototype.get_month_last = function (gap){
      // gap = gap + 1
      let date1 = new Date()
      // 获取下个月月初
      let gapMonth = date1.getMonth()
      gapMonth = gapMonth + 1 + gap

      let NextMonthFirstDay=new Date(date1.getFullYear(),gapMonth,1)
      NextMonthFirstDay = NextMonthFirstDay.getTime() - 1000*60*60*24
      let temp = new Date()
      temp.setTime(NextMonthFirstDay)
      let lastDay = this.format_date(temp)
      return lastDay
    };

    // 获取日期函数,若gap=0,则为系统日期,若不为0,则当期日期-gap(待参考)
    Vue.prototype.get_date = function (gap){
      let date = new Date()
      date = date.getTime() - 1000*60*60*24*gap
      let temp = new Date()
      temp.setTime(date)
      let day = this.format_date(temp)
      return day
    };

    // 时间戳转时间
    Vue.prototype.timestamp_to_time = function (gap){
     let year=new Date(now).getFullYear()
     let month=new Date(now).getMonth()+1
     let date=new Date(now).getDate()
     let hour=new Date(now).getHours()
     let minute=new Date(now).getMinutes()
     let second=new Date(now).getSeconds()
     return year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second; 
      // alert(page)
    };

};

在main.js中use

如此在各个地方都可以使用

1,获取1天前,7天前

2,获取上月初,上月末

若是三个月前月初this.get_month_first(-3)

猜你喜欢

转载自blog.csdn.net/gongpan2468/article/details/85782304
今日推荐