百度小程序日期+时间控件

百度小程序日期+时间控件

前言

由于百度小程序的smartui和自带的没有时间+日期的控件,正好项目有用到所以手写了一个日期+时间控件,上代码 (不喜勿喷,当然需要改善的地方大家可以提出来)

<view class="timeBox">
    <view class="pickertop">
        <view class="cancel posPicker" bindtap="cancel">取消</view>
        <view class="confirm posPicker" bindtap="confirm">确定</view>
    </view>
    <picker-view bindchange="change" value="{{pickerIndex}}" style="width: 100%; height:500rpx;padding-left:60rpx;z-index:1000;">
        <!-- 年 -->
        <picker-view-column>
           <view style="line-height:34px;" s-for="yearList">{{item}}年</view>
        </picker-view-column>
        <!-- 月 -->
        <picker-view-column>
           <view style="line-height:34px;" s-for="monthList">{{item}}月</view>
        </picker-view-column>
        <!-- 日 -->
        <picker-view-column>
           <view style="line-height:34px;" s-for="dateList">{{item}}日</view>
        </picker-view-column>
        <!-- 时 -->
        <picker-view-column>
           <view style="line-height:34px;" s-for="hourList">{{item}}</view>
        </picker-view-column>
        <!-- 分 -->
        <picker-view-column>
           <view style="line-height:34px;" s-for="minuteList">{{item}}</view>
        </picker-view-column>
    </picker-view>
</view>
<view class="bg" bindtap="cancel"></view>
.timeBox{
    background-color:#ffffff;
    width:100vw;
    position:fixed;
    bottom:0;
    z-index:1000;
}
.posPicker{
    padding:16rpx;
    box-sizing: border-box;
}
.cancel{
    left:0;
    top:0;
    color:#969799;
}
.confirm{
    right:0;
    top:0;
    color:#576b95;
}
.pickertop{
    z-index:100;
    position:absolute;
    top:0;
    left:0;
    width:100vw;
    display:flex;
    justify-content:space-between;
    align-items:center;
    background-color: #ffffff;
}
.bg{
    width: 100vw;
    height: 100vh;
    background-color: rgba(0,0,0,.5);
    position:fixed;
    left:0;
    top:0;
    z-index:999;
}

const times=new Date()
Component({
    properties: {
        value:{//当前日期时间(年+月+日 时:分)
            type:String,
            default:times.getFullYear()+'/'+(times.getMonth()+1)+'/'+times.getDate()+' '+times.getHours()+':'+times.getMinutes()
        },
        maxDate:{//最大日期时间(年+月+日 时:分)
            type:String,
            default:Date.now(),
        }
    },

    data: {
        yearList:[],//年
        monthList:[],//月
        dateList:[],//日
        hourList:[],//时
        minuteList:[],//分
        year:null,//当前年
        month:null,//当前月
        day:null,//当前天
        hour:null,//当前小时
        minutes:null,//当前分
        pickerIndex:undefined,//
        indexs:[],//picker change事件返回的索引值
        timeFalg:false,//是否小于传入组件的时间
    }, // 私有数据,可用于模版渲染

    // 生命周期函数,可以为函数,或一个在methods段中定义的方法名
    attached: function () {
        // console.log(this.data.value)
        // console.log(this.data.maxDate)
        this.handleData()//处理数据
        this.getYear()
        this.getMonth()
        this.getDays()
        this.getHours()
        this.getMinutes()
        this.setPickerIndex()//设置选中的索引
    },

    detached: function () {},

    methods: {
        //设置选中的索引
        setPickerIndex(){
            let {value,yearList,monthList,dateList,hourList,minuteList}=this.data
            let timeStr=new Date(value.replace(/-/g,'/'))
            let year=timeStr.getFullYear()
            let month=timeStr.getMonth()+1
            let date=timeStr.getDate()
            let minutes=timeStr.getMinutes()
            let hour=timeStr.getHours()
            let indexY=yearList.findIndex(elm=>elm==year)
            let indexM=monthList.findIndex(elm=>elm==month)
            let indexD=dateList.findIndex(elm=>elm==date)
            let indexH=hourList.findIndex(elm=>elm==hour)
            let indexm=minuteList.findIndex(elm=>elm==minutes)
            this.setData({pickerIndex:[indexY,indexM,indexD,indexH,indexm]})
        },
        //判断时间是否小于组件传来的时间
        judge(){
            //判断当前选中时间是否小于日期控件进入的时间
            let {maxDate,yearList,monthList,dateList,hourList,minuteList,timeFalg,indexs}=this.data
            let year=yearList[indexs[0]],
                month=monthList[indexs[1]],
                day=dateList[indexs[2]],
                hour=hourList[indexs[3]],
                minutes=minuteList[indexs[4]];
            let time=new Date(year+'/'+month+'/'+day+' '+hour+':'+minutes).
            getTime()
            if(time<new Date(maxDate.replace(/-/g,'/'))){
                timeFalg=true
                this.setData({
                    year,month,day,hour,minutes
                })
            }else{
                timeFalg=false
                this.setData({
                    year:new Date(maxDate.replace(/-/g,'/')).getFullYear(),
                    month:new Date(maxDate.replace(/-/g,'/')).getMonth()+1,
                    day:new Date(maxDate.replace(/-/g,'/')).getDate(),
                    hour:new Date(maxDate.replace(/-/g,'/')).getHours(),
                    minutes:new Date(maxDate.replace(/-/g,'/')).getMinutes(),
                })
                console.log(this.data.pickerIndex)
            }
            this.setData({
                timeFalg,
            })
        },
        //设置年月日时间
        setValue(){
            let {indexs,yearList,monthList,dateList,hourList,minuteList}=this.data
            this.setData({
                year:yearList[indexs[0]],
                month:monthList[indexs[1]],
                day:dateList[indexs[2]],
                hour:hourList[indexs[3]],
                minutes:minuteList[indexs[4]],
            })
        },
        confirm(){
            let {year,month,day,hour,minutes,}=this.data
            let time=`${year}/${month}/${day} ${hour}:${minutes}`
            this.triggerEvent('confirm',time)
        },
        cancel(){
            this.triggerEvent('cancel')
        },
        change(ev){
            // console.log(ev)
            this.setData({
                indexs:ev.detail.value,
            })
            this.judge()//判断并且设置选择的时间是否小于进入时间
            // this.getYear()
            this.getMonth()
            this.getDays()
            this.getHours()
            this.getMinutes()
            if(!this.data.timeFalg){
                this.setData({
                    pickerIndex:[100,100,100,100,100]
                })
            }
        },
        //传入的时间戳转换成年月日
        handleData(){
            let {maxDate,value,timeFalg}=this.data
            let time=new Date(maxDate.replace(/-/g,'/'))
            timeFalg=new Date(value.replace('-','/')).getTime()<time.getTime()?true:false
            this.setData({
                year:time.getFullYear(),//当前月
                month:time.getMonth()+1,//当前年
                day:time.getDate(),//当前天
                hour:time.getHours(),//小时
                minutes:time.getMinutes(),//分钟
                timeFalg,
            })
        },
        //获取年
        getYear(){
            //年列表
            let yearList=[]
            for(let i=0;i<=10;++i){
                yearList.unshift(this.data.year-i)
            }
            this.setData({yearList})
        },
        //查询月
        getMonth(){
            let {month,timeFalg, maxDate,year}=this.data
            this.setData({
                monthList:[]
            })
            let monthList=[]
            if(year>=new Date(maxDate.replace(/-/g,'/')).getFullYear()){
                month=new Date(maxDate.replace(/-/g,'/')).getMonth()+1
            }else{
                !timeFalg?'':month=12
            }
            for(let i=0;i<month;++i){
                monthList.push(i+1<10?'0'+(i+1):i+1)
            }
            this.setData({monthList})
        },
        //判断当前月有几天
        getDays(){
            let {maxDate,year,day,month,timeFalg}=this.data
            if(new Date(maxDate.replace(/-/g,'/')).getFullYear()==year && new Date(maxDate.replace(/-/g,'/')).getMonth()+1 ==month && !timeFalg){
                day=new Date(maxDate.replace(/-/g,'/')).getDate()
            }else{
                if(timeFalg){
                    if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12){
                        day= 31
                    }else if(month==4 || month==6 || month==9 || month==12){
                        day= 30
                    }else{
                        if((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)){
                            day= 28
                        }else{
                            day= 29
                        }
                    }
                }
            }
            // console.log(day)
            //日列表
            this.setData({
                dateList:[]
            })
            let dateList=[]
            for(let i=0;i<day;++i){
                dateList.push(i+1<10?'0'+(i+1):i+1)
            }
            this.setData({dateList})
        },
        //获取小时
        getHours(){
            let {hour,timeFalg,maxDate,year,month,day}=this.data
            if(new Date(maxDate.replace(/-/g,'/')).getFullYear()==year && new Date(maxDate.replace(/-/g,'/')).getMonth()+1 ==month && new Date(maxDate.replace(/-/g,'/')).getDate()==day && !timeFalg){
                hour=new Date(maxDate.replace(/-/g,'/')).getHours()
            }else{
                !timeFalg?'':hour=23
            }
            this.setData({
                hourList:[]
            })
            let hourList=[]
            for(let i=0;i<=hour;++i){
                hourList.push(i<10?'0'+i:i)
            }
            this.setData({hourList})
            // console.log(hourList)
        },
        //获取分钟
        getMinutes(){
            let {timeFalg,maxDate,year,month,day,hour,minutes}=this.data
            if(new Date(maxDate.replace(/-/g,'/')).getFullYear()==year && new Date(maxDate.replace(/-/g,'/')).getMonth()+1 ==month && new Date(maxDate.replace(/-/g,'/')).getDate()==day && new Date(maxDate.replace(/-/g,'/')).getHours()==hour && !timeFalg){
                minutes=new Date(maxDate.replace(/-/g,'/')).getMinutes()
            }else{
                !timeFalg?'':minutes=59
            }
            this.setData({
                minuteList:[]
            })
            let minuteList=[]
            for(let i=0;i<=minutes;++i){
                minuteList.push(i<10?'0'+i:i)
            }
            this.setData({minuteList})
            // console.log(minuteList)
        },
        onTap: function () {
            this.setData({
                // 更新属性和数据的方法与更新页面数据的方法类似
            });
        }
    }
});

总结

感觉写的挺乱的,不喜勿喷。需要改善的地方大家可以提出来。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
A:小程序时间选择控件可以使用小程序自带的组件picker来实现,具体代码如下所示: ```html <view class="picker"> <picker mode="date" start="{{today}}" end="{{endDate}}" value="{{date}}" bindchange="onDateChange"> <view class="picker-text">{{date | date}}</view> </picker> </view> ``` 其中,`mode="date"`表示选择器的类型为日期选择器,`start="{{today}}"`表示可选择的起始日期为今天,`end="{{endDate}}"`表示可选择的截止日期为endDate。`value="{{date}}"`表示选择器的默认值为date变量所代表的日期,`bindchange="onDateChange"`表示当选择器的值发生改变时,会调用onDateChange函数进行处理。`<view class="picker-text">{{date | date}}</view>`表示选择器下方显示的文字为date变量所代表的日期(使用格式化器"date"来格式化日期)。 在JS文件中,可以通过setData()方法来更新date变量的值,从而实现时间选择控件的功能。具体代码如下所示: ```javascript Page({ data: { today: new Date().getTime(), endDate: new Date(new Date().getTime() + 360 * 24 * 60 * 60 * 1000).getTime(), //可选择的截止日期为今天后的360天 date: null //表示当前选择的日期 }, onDateChange: function (e) { this.setData({ date: e.detail.value }) } }) ``` 其中,`today`代表今天的日期,`endDate`代表可选择的截止日期(这里设置为今天的后360天),`date`代表当前选择的日期,初始值为null。当用户选择日期时,会触发onDateChange函数,从而更新date变量的值。最后,可以通过格式化器"date"将date变量的值进行格式化,从而在页面上显示用户选择的日期。 以上代码仅供参考,具体实现方式还需根据实际需求进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值