后端返回的时间格式是时间戳,需要以年月日的格式渲染在前端界面
由于uniapp是基于vue的,所以对于时间的处理。我们也可以用到
过滤器。

1:在uniapp的项目的static目录底下,新建一个test.json文件,

 
 

test.json里面写好模拟数据(未处理的时间戳)

{
"time":"1588061853944"
}

2:步骤:
写一个请求方法请求json数据,在data里面定义一个数组,将请求成功的数据赋值给数组,然后再渲染的view里面,这个步骤就不多说了,常规操作哦。

这里要用到filters过滤的方法,时间戳的处理其实和jquery里面用到的是一样的。

 <view class="text-cut">
            {{timeArray.time | formatDate}}
 </view>
 //时间戳的处理    
        filters: {
            formatDate: function(value) {
                var date = new Date();
                //date.setTime(value);
                var month = date.getMonth() + 1;
                var hours = date.getHours();
                if (hours < 10)
                    hours = "0" + hours;
                var minutes = date.getMinutes();
                if (minutes < 10)
                    minutes = "0" + minutes;
                var time = date.getFullYear() + "-" + month + "-" + date.getDate() +
                    " " + hours + ":" + minutes;
                return time;
            }

        },

3:完整的示例代码如下index.vue

<template>
    <view>
        <view class="text-cut">
            {{timeArray.time | formatDate}}
        </view>
    </view>
</template>
<script>
    export default {
        data() {
            return {
                timeArray: [],
            };
        },
        onLoad() {
            this.getList();
        },
        methods: {
            getList() {
                uni.request({
                    url: "../../static/test.json",
                    method: 'get',
                    dataType: 'json',
                    success: (res) => {
                        console.log(res.data);
                        this.timeArray = res.data;
                    },
                    // fail: function (err) {
                    //        console.log("服务器繁忙")
                    // }                
                });
            },
    
        },
        //时间戳的处理    
        filters: {
            formatDate: function(value) {
                var date = new Date();
                //date.setTime(value);
                var month = date.getMonth() + 1;
                var hours = date.getHours();
                if (hours < 10)
                    hours = "0" + hours;
                var minutes = date.getMinutes();
                if (minutes < 10)
                    minutes = "0" + minutes;
                var time = date.getFullYear() + "-" + month + "-" + date.getDate() +
                    " " + hours + ":" + minutes;
                return time;
            }

        },
    }
</script>
<style>
</style>

4:显示结果如下

 
 
 
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐