Ext JS:无论浏览器时区如何,都以UTC显示日期

Ext JS: Display dates in UTC regardless of browser timezone

本文关键字:都以 UTC 日期 显示 时区 JS 浏览器 Ext      更新时间:2023-09-26

在Ext JS网格中强制日期以UTC(并忽略浏览器本地时间)显示的最佳方法是什么?

我的模型接收UTC的日期:

"2014-06-24T00:00:00+00:00"

我的网格有一个日期列:

Ext.define('MyApp.view.MyGrid', {
    store: MyApp.store.MyStore,
    columns: [
        {
            xtype: 'datecolumn',
            text: 'Date',
            dataIndex: 'date',
            format: 'Y-m-d H:i:sO'
        },
    ]
});

日期以浏览器本地时间显示,例如:

2014-06-24 01:00:00+0100

但是我想用UTC显示它们

到目前为止,我找到的最好的解决方案是导入moment.js并这样使用它:
{
    xtype: 'datecolumn',
    text: 'Date',
    dataIndex: 'date',
    renderer: function (value) {
        return moment.utc(value).format('YYYY-MM-DD HH:mm:ssZZ');
    }
}

有想要的结果:

2014-06-24 00:00:00+0000

肯定有更干净的方法吧?

我没有看到内置的UTC支持,因此您可以扩展datecolumn并使用moment来呈现日期。例子:

Ext.define('Ext.grid.column.UtcDate', {
    extend: 'Ext.grid.column.Date',
    alias: ['widget.utcdatecolumn'],
    alternateClassName: 'Ext.grid.UtcDateColumn',
    defaultRenderer: function(value){
        return moment.utc(value).format(this.format);
    }
});

utcdatecolumn代替datecolumn:

Ext.define('MyApp.view.MyGrid', {
    store: MyApp.store.MyStore,
    columns: [
        {
            xtype: 'utcdatecolumn',
            text: 'Date',
            dataIndex: 'date',
            format: 'YYYY-MM-DD HH:mm:ssZZ'
        }
    ]
});

它存在于最新的ExtJs中。使用toUTCstring()或其他可用的toUTC xxxx()方法。

或者,可以这样做:

// convert to msec
// add local time zone offset 
// get UTC time in msec
utc = d.getTime() + (d.getTimezoneOffset() * 60000);