本文介绍了如何在ExtJS4.1模型中将时间戳转换为自定义日期格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在服务器返回数据之后将时间戳转换为自定义日期格式。
我试图在Ext.data.field中使用convert:

I want to convert the timestamp to customized date format right after the server returns the data.I tried to use the "convert" in Ext.data.field : http://docs.sencha.com/ext-js/4-1/#!/api/Ext.data.Field-cfg-convert

但我不能做到正确。这是我的模型。

But I cannot make it right. This is my model.

Ext.define('AM.model.Comment',{
    extend: 'Ext.data.Model',
    fields: [
        { name: 'createdTime', type: 'date', convert:function(v,record){record.parseDate(v,record);}}, // datetime
    ],

    proxy: {
        type: 'rest',
        url:'../comments',
        writer:{
            type:'json'
        },
        reader: {
            type: 'json'
        }
    },
    parseDate:function(v,record){
        console.log(v); //show 1347465600000
        console.log(Ext.Date.format(new Date(v), 'Y-m-d')); //show 2012-09-13
        return Ext.Date.format(new Date(v), 'Y-m-d');
    }
});

加载完成后,我查看了firebug,发现createdTime字段是undefined。
有人可以指出我的错误吗?谢谢!

After loading, I checked firebug and found the field "createdTime" is "undefined".Can someone point out my mistake? Thanks!

我可以实现没有使用转换,只需使用 Ext.Date.format(new Date(v),'Ym- d')在其他组件。但是我认为在模型中做得更好。然后,每个组件都可以随时查询正确的日期格式。

I can achieve that without using "convert", just use Ext.Date.format(new Date(v), 'Y-m-d') in other component. But I think it will be better to do that in model. Then every component can always read the right date format as querying it.

推荐答案

我找到了一个解决方案。而不是使用转换,我覆盖读者的getData()方法。

I found a solution. Instead of using "convert", I override the getData() method of reader.

Ext.define('AM.model.Comment',{
    extend: 'Ext.data.Model',
    fields: [
        { name: 'createdTime', type: 'datetime'},
    ],

    proxy: {
        type: 'rest',
        url:'../comments',
        writer:{
            type:'json'
        },
        reader: {
            type: 'json',
            getData:function(data){
                for(i = 0; i < data.length; i++){
                    data[i].createdTime = Ext.Date.format(new Date(data[i].createdTime), "Y-m-d");
                }
                return data;
            }
        }
    }
});

如果有人有更好的解决方案,请告诉我。我还是想知道为什么转换不起作用。如果有人知道原因,请告诉我。谢谢!

If anyone has better solution, please tell me. And I still wonder why "convert" didn't work.If anyone know the reason, please tell me, too. Thanks!

这篇关于如何在ExtJS4.1模型中将时间戳转换为自定义日期格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 14:14
查看更多