# moment相关时间获取

# 安装

npm install moment
1

# 主文件引入

// 导入
import moment from 'moment'
// 挂载到原型上
Vue.prototype.$moment = moment;
1
2
3
4

# 今天

moment().format("YYYY-MM-DD")
1

# 昨天

moment().subtract(1, 'days').for("YYYY-MM-DD")
1

# 本周

用自己封装的方法实现 (moment以上周日到本周六为一周, 少了一天)

# 封装的日期方法

getTime (n) {
    var now = new Date();
    var year = now.getFullYear();
    var month = now.getMonth() + 1;
    var day = now.getDay(); //返回星期几的某一天;
    n = day == 0 ? n + 6 : n + (day - 1)
    now.setDate(now.getDate() - n);
    var date = now.getDate();
    var s = year + "-" + (month < 10 ? ('0' + month) : month) + "-" + (date < 10 ? ('0' + date) : date);
    return s;
 }
1
2
3
4
5
6
7
8
9
10
11

# 使用

//本周的开始时间
this.currentStartDate = this.getTime(0);
//本周的结束时间
this.currentEndDate = this.getTime(-6);
1
2
3
4

# 上周

用自己封装的方法实现 (见上方)

//上周的开始时间
this.currentStartDate = this.getTime(7);
//上周的结束时间
this.currentEndDate = this.getTime(1);
1
2
3
4

# 本月

// 本月初
moment().startOf('month').format('YYYY-MM-DD')
// 本月末
moment().endOf('month').format('YYYY-MM-DD'); 
1
2
3
4

# 上月

// 上月初
moment().month(moment().month() - 1).startOf('month').format("YYYY-MM-DD");
// 上月末
moment().month(moment().month() - 1).endOf('month').format("YYYY-MM-DD")
1
2
3
4

# 今年

// 年初
moment().startOf('year').format("YYYY-MM-DD");
// 年末
moment().endOf('year').format("YYYY-MM-DD");
1
2
3
4

# 去年

// 去年初
moment().year(moment().year()-1).startOf('year').format("YYYY-MM-DD");
// 去年末
moment().year(moment().year()-1).endOf('year').format("YYYY-MM-DD");
1
2
3
4

# 前年

// 前年初
moment().year(moment().year()-2).startOf('year').format("YYYY-MM-DD");
// 前年末
moment().year(moment().year()-2).endOf('year').format("YYYY-MM-DD");
1
2
3
4
上次更新: 2021/6/2 上午10:36:46