uniapp時間格式化處理


應用需求分析:前台頁面有時需要展示YYYY-MM-DD格式,但后台卻返回給我們YYYY-MM-DD hh:mm:ss、或者是一串字符

一、通用的時間轉換方法如下:

//格式化處理
            dateFormat(time) {
                let date = new Date(time);
                let year = date.getFullYear();
                // 在日期格式中,月份是從0開始的,因此要加0,使用三元表達式在小於10的前面加0,以達到格式統一  如 09:11:05
                let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
                let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
                let hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
                let minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
                let seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
                // 拼接
                // return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
                return year + "-" + month + "-" + day;
            },

頁面使用如下:

<view v-if="item.rukudate">{{ dateFormat(item.rukudate) }}</view>

也可以通過三元運算符和當前時間對比

<view v-if="item.yuyuedate" :class="dateFormat(item.yuyuedate) == day ? 'sameDay' : '' ">{{ dateFormat(item.yuyuedate) }}</view>

 二、過濾器

思路:在過濾中寫一個時間處理方法,分別選取年月日,月份和日期需要01 02這種展示效果,需要用toString轉化截圖前兩項,然后拼接返回

// 時間過濾器
        filters:{
            formatDate(date){
                console.log(date)
                let newDate = new Date(date);
                let year = newDate.getFullYear();
                let month = newDate.getMonth().toString().padStart(2,0);
                let day = newDate.getDay().toString().padStart(2,0);
                return year + '-' + month + '-' + day;
            }
        },

頁面引用如下

<view>發表時間:{{ item.add_time | formatDate }}</view>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM