Matt Jenkins
Matt Jenkins

Reputation: 3081

Ext JS: Display dates in UTC regardless of browser timezone

What is the best way of forcing dates to display in UTC (and ignore the browser local time) in an Ext JS grid?

My model receives dates in UTC:

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

My grid has a datecolumn:

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

The dates are displayed in browser local time, e.g.:

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

But I want to display them in UTC.

So far, the best solution I have found is to import moment.js and use it thus:

{
    xtype: 'datecolumn',
    text: 'Date',
    dataIndex: 'date',
    renderer: function (value) {
        return moment.utc(value).format('YYYY-MM-DD HH:mm:ssZZ');
    }
}

Which has the desired result:

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

Surely there is a cleaner way?

Upvotes: 2

Views: 7057

Answers (2)

Snehal Masne
Snehal Masne

Reputation: 3429

Its there in latest ExtJs. Make use of toUTCstring() or other toUTC xxxx() methods available.

alternatively, can do below:

// convert to msec
// add local time zone offset 
// get UTC time in msec

utc = d.getTime() + (d.getTimezoneOffset() * 60000);

Upvotes: 3

Krzysztof
Krzysztof

Reputation: 16140

I don't see UTC support built-in, so you can for example extend datecolumn and use moment to render date. Example:

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);
    }
});

Then just use utcdatecolumn instead datecolumn:

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

Upvotes: 3

Related Questions