vue 移动端获取今日、昨日、本周、上周、本月、上月 日期时间

博主因移动端项目需求,需获取今日、昨日等日期时间,遂根据需求封装方法。介绍了使用Moment.js的步骤,包括安装、引入、封装方法、在页面引入及使用,还提醒根据后端需求处理时分秒,希望能帮助有相同需求的人。

近日移动端项目需求,要求获得今日、昨日、本周、上周、本月、上月 的用户数据,因此查了一些文档之类的根据需求封装了几个方法,如果你的需求同我一样,那么你可以直接拷贝,按照步骤去使用即可。话不多说直接上代码:

npm install moment --save
  • 第二步:在需要用到的页面引入 如第三步引入
import moment from "moment";
  • 第三步:在项目中新建一个js文件,封装获取时间的方法,这里我已经写好了,需要的直接把代码拷贝进去即可。
  • 因我我们后台的需要让把年月日 时分秒 都传过去,所以请注意:( 代码中的 HH:mm:ss 就是时分秒的转换)如果你们后端不需要你传时分秒,那么你就直接删除  HH:mm:ss 即可。
// 引入 moment 时间插件
import moment from "moment";
//获取今日/昨日/本周/上周/本月/上月 时间
export default {
    // 获取今日的开始结束时间
    getToday() {
        let obj = {
            starttime: '',
            endtime: ''
        }
        obj.starttime = moment(moment().startOf("day").valueOf()).format("YYYY-MM-DD HH:mm:ss");
        obj.endtime = moment(moment().valueOf()).format("YYYY-MM-DD HH:mm:ss");
        return obj
    },
    // 获取昨日的开始结束时间
    getYesterday() {
        let obj = {
            starttime: '',
            endtime: ''
        }
        obj.starttime = moment(moment().add(-1, 'days').startOf("day").valueOf()).format("YYYY-MM-DD HH:mm:ss");
        obj.endtime = moment(moment().add(-1, 'days').endOf('day').valueOf()).format('YYYY-MM-DD HH:mm:ss');
        return obj
    },
    // 获取当前周的开始结束时间
    getCurrWeekDays() {
        let obj = {
            starttime: '',
            endtime: ''
        }
        obj.starttime = moment(moment().week(moment().week()).startOf('week').add(1, 'days').valueOf()).format('YYYY-MM-DD HH:mm:ss')
        obj.endtime = moment(moment().week(moment().week()).endOf('week').add(1, 'days').valueOf()).format('YYYY-MM-DD HH:mm:ss');
        return obj
    },
    // 获取上一周的开始结束时间
    getLastWeekDays() {
        let obj = {
            starttime: '',
            endtime: ''
        }
        obj.starttime = moment(moment().week(moment().week() - 1).startOf('week').add(1, 'days').valueOf()).format('YYYY-MM-DD HH:mm:ss')
        obj.endtime = moment(moment().week(moment().week() - 1).endOf('week').add(1, 'days').valueOf()).format('YYYY-MM-DD HH:mm:ss');
        return obj
    },
    // 获取当前月的开始结束时间
    getCurrMonthDays() {
        let obj = {
            starttime: '',
            endtime: ''
        }
        obj.starttime = moment(moment().month(moment().month()).startOf('month').valueOf()).format('YYYY-MM-DD HH:mm:ss');
        obj.endtime = moment(moment().month(moment().month()).endOf('month').valueOf()).format('YYYY-MM-DD HH:mm:ss');
        return obj
    },
    // 获取上一个月的开始结束时间
    getLastMonthDays() {
        let obj = {
            starttime: '',
            endtime: ''
        }
        obj.starttime = moment(moment().month(moment().month() - 1).startOf('month').valueOf()).format('YYYY-MM-DD HH:mm:ss');
        obj.endtime = moment(moment().month(moment().month() - 1).endOf('month').valueOf()).format('YYYY-MM-DD HH:mm:ss');
        return obj
    },


}

 

  • 第四步:在需要获取时间的页面引入(路径改成自己的文件路径即可,其他的不需要改)
import getDate from "./getDate";
  • 第五步:使用方法(在created里面测试下是否能获取到,获取到的时间是否正确,如果无误再按照自己的需求在data里面定义变量,在需要的地方获取时间并赋值。以下是我给出的测试案例,可以直接拷贝,然后看下图,如果可以拿到时间,证明无误)
  created() {
    // 今日开始时间
    let endtime = getDate.getToday().endtime;
    //今日结束时间
    let starttime = getDate.getToday().starttime;
    console.log("获取时间今日时间");
    console.log(getDate.getToday());
    console.log(starttime);
  },
  • 如下图所示: 

  • 以上就是我遇到的问题以及实现步骤,希望可以帮到你。有兴趣的可以关注我,互相学习。
    我时常会整理博客,工作中遇到的问题和常用需求都会写出小案例放在博客上以供大家一起参考和使用。 
  • 有问题的可留言,我会即使处理回答,谢谢?
这是我的 uniapp 制作一个筛选功能 调用组件页面: <fu-filter-dropdown :top="CustomBar" @changeFilter="changeFilter"></fu-filter-dropdown> 组件页面: 还没有写 我希望是 跟图片一样的 右侧弹窗的 , 能够选择 :1.开始时间 2.结束时间 3.快速选择: 本周 上周 本月 上月 近15天 近30天的; 4.仓库列表 ,5.供应商列表,6.订单状态列表 ; 其中4,5,6随便弄点假数据就行 预留出接口位置 , 然后最后还需要 清空所有筛选条件 , 然后这个右侧弹窗的 底部 有两个按钮 确定 和 关闭 ; 目的就是 确定之后 我要进行传给父页面 请求接口数据的 这是组件目前代码: 完全可以替我修改掉 里面代码都是没用不相关的 <template> <view id="wrapper" class="wrapper bg-white solid-bottom" :style="[{top: top+'px'}]"> <view id="content1" class="padding-lr flex content1 " style="height: 108rpx;"> <view class="flex"> <view class=" flex align-center justify-end" @click="drawerhandle"> <!-- <text class="text-999 text-sm">{{i18n['筛选']}}</text> --> <image src="/static/shaixuan.png" style="width: 40rpx;height: 40rpx;" mode=""></image> </view> </view> </view> <fu-popup v-model="showDrawer" mode="right" :safe-area-inset-bottom="true" :border-radius="0" width='70%'> <view class="container " :style="[{paddingTop: StatusBar+'px'}]"> <scroll-view class="pop-content" scroll-y> <view class="title" style="font-size: 36rpx;margin-bottom: 30rpx;text-align: center;"> {{i18n['筛选']}} </view > <view class="brand title" style="font-size: 32rpx;" v-if='brandList.length != 0'> 选购方式 </view> <view class='service serviceItem' v-if='xuangoulist.length !=0'> <text v-for='(items,indexs) in xuangoulist' class="list-item ml-4 padding-tb-xs padding-lr text-sm text-333 radius-16" :class="xuanGouIndex == indexs? 'active2':''" @click='openSelectXuanGou(indexs)'>{{items.name}}</text> <text></text> </view> <view class="brand title" style="font-size: 32rpx;" v-if='brandList.length != 0'> {{i18n['品牌']}} </view> <view class='service serviceItem' v-if='brandList.length !=0'> <text v-for='item in brandList' class="list-item ml-4 padding-tb-xs padding-lr text-sm text-333 radius" :class="[{'active2': item.selected}]" @click='Choice(item)'>{{item.brand_name}}</text> <text></text> </view> <view class="title" style="font-size: 32rpx;"> {{i18n['价格']}} </view> <view class='service serviceItem' v-if='priceList.length !=0'> <text v-for='(item,index) in priceList' class="list-item ml-4 padding-tb-xs padding-lr text-sm text-333 radius-16" :class="priceActiveIndex == index? 'active2':''" @click='ChoicePrice(index,item)'>{{item.name}}</text> <text></text> </view> <view class='price-round flex align-center'> <view class="list-item low-price"> <input :placeholder="i18n['最低价']" type="number" v-model='minVal' maxlength="10" @confirm="getGoodNumber" > </view> <view class="border-center">-</view> <view class="list-item ml-4 low-price"> <input :placeholder="i18n['最高价']" type="number" v-model='maxVal' maxlength="10" @confirm="getGoodNumber" > </view> </view> </scroll-view> <view class="action-box pop-btn"> <view class="action reset" @tap.stop="resetPop">{{i18n['重置']}}</view> <!-- <view class="action confirm" @tap.stop="confirmPop">确定<text v-if='num || num ==0'>({{num | formatNumber('w+')}}件商品)</text></view> --> <view class="action confirm" @tap.stop="confirmPop">{{i18n['确定']}}</view> </view> </view> </fu-popup> </view> </template> <script> export default { props: { top: { type: [String, Number], default: 0, }, filterKeyword:{ type:[String] }, cid:{ type:[String,Number] } }, data() { return { num:0, // 高级搜索结束商品数量显示 minVal:'',// 最小价格 maxVal:'', // 最大价格 goodsSkuList:[], // 高级筛选商品sku列表 goodsServiceLabel:[], // 服务 brandList:[], // 品牌 typeList:[], // 分类 allTypeList:[], // 总分类 typeVal:'', // 高级搜索cid 商品id showDrawer:false, selects: [ { title: global.i18n['综合'], type: 'multiple' } ], // 综合 curSelected: 0, // 综合排序初始值 curFilter: 0, // 价格排序方式 filterType: 'multiple', // 排序类型 order: 'asc', // 升序:asc 倒序:desc model: 'block', // inline block windowWidth: 0, // 页面宽 windowHeight: 0, // 页面高 xuanGouIndex: -1, choose_type: '', xuangoulist: [{ name: '线上购买', type: 0 }, { name: '到店自提', type: 1 }], priceList: [{ name: '0-90'+global.i18n['元'], minVal: '0', maxVal: '99', }, { name: '100-199'+global.i18n['元'], minVal: '100', maxVal: '199', }, { name: '200-299'+global.i18n['元'], minVal: '200', maxVal: '299', }, { name: '300-599'+global.i18n['元'], minVal: '300', maxVal: '599', }, { name: '599'+global.i18n['元']+'+', minVal: '599', maxVal: '9999999', }], }; }, watch:{ // filterKeyword(newVal,oldVal){ // console.log('filterKeyword',newVal) // this.resetPop(); // }, 'filterKeyword':{ handler(newVal,oldVal){ console.log('XXXXXXXXXXXXXXXXXXXXXXXXXX') this.resetPop(); }, immediate:true, } }, mounted(){ // this.getListData() // this.getGoodNumber() }, methods: { openSelectXuanGou(index) { this.xuanGouIndex = index this.choose_type = this.xuangoulist[index].type console.log(this.choose_type); this.$forceUpdate() }, // 选 初始价格 ChoicePrice(index, item) { console.log('----------1111111') if (this.priceActiveIndex == index) { this.priceActiveIndex = '99' this.priceList.maxVal = '' this.priceList.minVal = '' return false } else { this.priceList.maxVal = item.maxVal this.priceList.minVal = item.minVal } this.priceActiveIndex = index this.$forceUpdate() }, // sku筛选 selectSkuListChoice(item){ this.$set(item, 'selected', !item.selected); this.getGoodNumber() }, // 获取商品数量 getGoodNumber(){ // 获取已选中的服务 let goodsServiceLabel =[]; this.goodsServiceLabel.forEach(item=>{ if(item.selected){ goodsServiceLabel.push(item.label_id) } }) // 获取已选中的品牌 let brandList =[]; this.brandList.forEach(item=>{ if(item.selected){ brandList.push(item.brand_id) } }) // 获取已选择的sku内容 let skuList =[]; console.log(this.goodsSkuList ) for(let obj in this.goodsSkuList ){ this.goodsSkuList[obj].forEach(j=>{ if(j.selected){ skuList.push(j.id) } }) } skuList =skuList.join(',') brandList= brandList.join(',') goodsServiceLabel= goodsServiceLabel.join(',') // console.log(this.typeVal,this.minVal,this.maxVal,brandList,goodsServiceLabel) if(this.minVal && this.maxVal){ if(Number(this.minVal) > Number(this.maxVal)){ [this.minVal,this.maxVal] =[this.maxVal,this.minVal] } } // 判断cid存在(分类页过来的时候直接使用) if(this.cid){ this.typeVal = this.cid } let filterObj={ sku_id:skuList, brand_id:brandList, goods_cid:this.typeVal, service_lable_id:goodsServiceLabel, min_price: Number(this.minVal).toFixed(2), max_price: Number(this.maxVal).toFixed(2), keyword:this.filterKeyword } this.$api.post(global.apiUrls.getGoodNumber, filterObj) .then(res => { console.log('搜索商品数量', res.data) if (res.data.code == '1') { this.num = res.data.data } else { this.$message.error(res.data.msg); } }) }, // 品牌筛选 Choice(item){ this.$set(item, 'selected', !item.selected); this.goodsSkuList =[] if(this.allTypeList.allType.length >0){ this.getNewTypeListData() } this.getGoodNumber() }, //分类重置 去重 getNewTypeListData(){ this.typeVal ='' let newTypeData=[]; let deWeightData =[]; this.typeList =[] this.brandList.forEach((item,index)=>{ if(item.selected){ newTypeData = newTypeData.concat(this.allTypeList[item.brand_id]) newTypeData.forEach(item=>{ let flag =false; deWeightData.forEach(j=>{ if(j.cid == item.cid){ flag =true } }) if(!flag){ deWeightData.push(item) } }) } }) // console.log(deWeightData) this.typeList = deWeightData // 获取已选中的品牌 let brandList =[]; this.brandList.forEach(item=>{ if(item.selected){ brandList.push(item.brand_id) } }) // 未选中品牌,显示所有分类 if(brandList.length ==0){ this.typeList = this.allTypeList.allType } }, // 服务筛选 selectServeChoice(item){ this.$set(item, 'selected', !item.selected); this.getGoodNumber() }, // 分类筛选 selectTypeChoice(item){ this.goodsSkuList =[] if(this.typeVal == item.cid){ this.typeVal ='' }else{ this.typeVal = item.cid this.getGoodsSkuList(item.cid) } this.getGoodNumber() }, // 分类获取不同的sku信息 getGoodsSkuList(val){ console.log(1111111111,val) let data ={ goods_cid:val } this.$api.post(global.apiUrls.getGoodsSkuList, data) .then(res => { console.log('sku列表结果', res.data) if (res.data.code == '1') { console.log(res.data.data) this.goodsSkuList =res.data.data } else { this.$message.error(res.data.msg); } }) }, // 获取高级搜索得索引列表 getListData(){ let data ={ keyword: this.filterKeyword, goods_cid:this.cid } this.$api.post(global.apiUrls.advancedSearch, data) .then(res => { console.log('1111111111--------------->',res); if (res.data.code == 1) { data = res.data.data; this.goodsServiceLabel =data.goodsServiceLabel; this.brandList =data.brandList; this.typeList =data.typeList.allType; this.allTypeList =data.typeList } else { this.$message.error(res.data.msg); } }) }, // 重置筛选条件 resetPop() { this.priceList.minVal = '' this.priceList.maxVal = '' this.priceActiveIndex = '99' this.typeVal = '' this.minVal = '' this.maxVal = '' this.goodsSkuList = [] this.brandList = [] this.goodsServiceLabel = [] this.choose_type = '' // setTimeout(()=>{ this.getListData() this.getGoodNumber() this.confirmPop(false) // },200) }, // 提交确认高级筛选 confirmPop(val) { // 获取已选中的服务 let goodsServiceLabel =[]; this.goodsServiceLabel.forEach(item=>{ if(item.selected){ goodsServiceLabel.push(item.label_id) } }) // 获取已选中的品牌 let brandList =[]; this.brandList.forEach(item=>{ if(item.selected){ brandList.push(item.brand_id) } }) // 获取已选择的sku内容 let skuList =[]; console.log(this.goodsSkuList ) for(let obj in this.goodsSkuList ){ this.goodsSkuList[obj].forEach(j=>{ if(j.selected){ skuList.push(j.id) } }) } skuList =skuList.join(',') brandList= brandList.join(',') goodsServiceLabel= goodsServiceLabel.join(',') if(this.minVal && this.maxVal){ if(Number(this.minVal) > Number(this.maxVal)){ [this.minVal,this.maxVal] =[this.maxVal,this.minVal] } } let filterObj={ sku_id:skuList, brand_id:brandList, goods_cid:this.typeVal, service_lable_id:goodsServiceLabel, min_price: Number(this.minVal).toFixed(2), max_price: Number(this.maxVal).toFixed(2), choose_type: this.choose_type } // 判断是否有已选择时间,如有优先生效,并清空输入值 if (this.priceList.maxVal) { this.maxVal = '' this.minVal = '' filterObj.min_price = Number(this.priceList.minVal).toFixed(2) filterObj.max_price = Number(this.priceList.maxVal).toFixed(2) } this.curFilter = 0; this.isSearchShop = false; this.$emit('changeFilter', this.curFilter, this.order,filterObj); console.log(filterObj) if(!val) return ; console.log(val); this.showDrawer = false; // if(skuList!='' || brandList!='' || goodsServiceLabel!='' || Number(this.minVal).toFixed(2) !='0.00' || Number(this.maxVal).toFixed(2)!='0.00' || this.filterKeyword!=''){ // this.$emit('changeFilter', this.curFilter, this.order,filterObj); // if(!val) return ; // this.showDrawer = false; // }else{ // // this.$message.info('请选择或输入内容') // return // } }, // 上层筛选条件 async filterClick(type) { let oldType = this.curFilter; switch (type) { case 0: if (oldType != 0) { this.curFilter = 0; } this.order = 'asc'; break; case 1: // this.curFilter = 1; // this.order = 'desc'; if (oldType == 1) { if (this.order == 'asc') { this.order = 'desc'; } else { this.order = 'asc'; } } else { this.order = 'desc'; this.curFilter = 1; } break; case 2: if (oldType == 2) { if (this.order == 'asc') { this.order = 'desc'; } else { this.order = 'asc'; } } else { this.order = 'asc'; this.curFilter = 2; } break; case 3: this.curFilter = 3; this.order = 'asc'; break; } this.$emit('changeFilter', this.curFilter, this.order); }, // 打开筛选侧边弹窗 drawerhandle() { this.showDrawer = true; }, // 综合排序切换 selectHandle(index) { this.curSelected = index; this.filterType = this.selects[index].type; this.showTopPop = false; }, // 排列布局切换 changeLayout() { if (this.model == 'inline') { this.model = 'block'; } else { this.model = 'inline'; } this.$emit('changeFilter', this.curFilter, this.order); this.$emit('changeLayout', this.model); }, }, created() { let info = uni.getSystemInfoSync(); this.windowWidth = info.windowWidth; this.windowHeight = info.windowHeight; } } </script> <style lang="scss" scoped> .wrapper { position: sticky; z-index: 9999; .content1 { .right { width: 80rpx; position: relative; // padding-left: 20rpx; } // .right::after { // content: ""; // width: 2rpx; // height: 26rpx; // background-color: #999999; // position: absolute; // top: 50%; // left: 50%; // transform: translateX(-50%) translateY(-50%); // } } .content2 { padding: 0 30rpx 20rpx 30rpx; .left { width: calc(100% - 100rpx); white-space: nowrap; } .right { width: 100rpx; } } .masks { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background-color: transparent; display: flex; flex-direction: column; .top { background-color: rgba(0, 0, 0, 0); } .bot { flex: 1; background-color: rgba(0, 0, 0, 0.7); .container { border-radius: 0 0 16rpx 16rpx; background-color: #F5F5F5; padding: 30rpx; .scroll-view { max-height: 300rpx; } } } } .active { /* color: $theme !important; */ color: #FF7298; font-weight: bold; } .active2 { // box-shadow: inset 0 0 2rpx 2rpx $theme; // background-color: rgba(240, 35, 37, 0.1) !important; color: #FFFFFF; background: $theme; } .active3 { color: $theme !important; } .masks2 { position: fixed; top: 0; bottom: 0; right: 0; left: 0; background-color: rgba(0, 0, 0, 0.7); display: flex; justify-content: flex-end; .container { width: 70%; height: 100%; border-radius: 16rpx 0 0 16rpx; background-color: #FFFFFF; } } } .action-box { display: flex; margin-top: 30rpx; .action { flex: 1; height: 72rpx; line-height: 72rpx; border-radius: 62rpx 0px 0px 62rpx;; font-size: 24rpx; text-align: center; } .action+.action { margin-left: 4rpx; border-radius: 0px 62px 62px 0px; } .reset { color: $bgtheme; // background-color: #FFA264; background: rgba($color: #FF7298, $alpha: 0.15); } .confirm { color: #FFFFFF; background: $bgtheme; } } .block-28 { width: 28rpx; height: 28rpx; } .scale { font-size: 32rpx !important; &.cuIcon-triangleupfill{ line-height: 20rpx; } &.cuIcon-triangledownfill{ line-height: 20rpx; } } .translateTop { // transform: translateY(5rpx); /* */ } .translateBot { // transform: translateY(-5rpx); } .pop-btn { position: fixed; width: 100%; bottom: 0; padding: 20rpx; background: #fff; border-top: 1rpx solid #f1f1f1; margin-top: 0; } .pop-content { height: 92%; padding: 20rpx; padding-bottom: 120rpx; } .title { font-weight: 500; color: #333333; margin-top: 20rpx; } .list-item { background-color: #F6F7F9; display: inline-block; margin-bottom: 20rpx; } .low-price{ background: rgba(255, 255, 255, 0.39); border: 1rpx solid #D9D9D9; opacity: 1; border-radius: 8rpx; } .serviceItem{ display: flex; flex-wrap: wrap; justify-content: space-between; width: 100%; text{ width: 31%; margin: 0 0 16rpx 0; padding: 20rpx 0; text-align: center; border-radius: 8rpx; } } .ml-20 { margin-left: 20rpx; } .ml-4 { margin-left: 4rpx; } .service { margin-top: 20rpx; } .price-round{ padding: 20rpx 10rpx; .round{ padding: 10rpx 0; text-align: center; background: #fff; border: 1px solid #ccc; } } .price-round input{ font-size: 24rpx; height: 64rpx; padding:0 60rpx; } .border-center{ height: 50rpx; margin: 0 15rpx ; } .scale.cuIcon-triangledownfill{ line-height: 12rpx; } .scale.cuIcon-triangleupfill{ line-height: 12rpx; } </style>
09-26
评论 7
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值