3/12/2019

Kendo UI Grid date display issue


Problem:If you have a Date field shown on the grid, the display time will be variant based on the client's browser.
Reference:Use UTC on Both Client and Server
Real Case:Our Web Server and DB server are in timezone GMT-8 when we save a Date/Time into a field, the date/time displayed on the client side in timezone GMT-8 has no problem.  But the user in timezone GMT-5, the time will be added 3 hours.
For example, we can see the data saved in the server is 12/11/2018 17:12, the display in LAX has no problem.  But the display in JFK, it will be 12/11/2018 20:12.
Solution:
<script type="text/javascript">
        var onRequestEnd = function(e) {
            if (e.response.Data && e.response.Data.length) {
                var data = e.response.Data;
                if (this.group().length && e.type == "read") {
                    handleGroups(data);
                } else {
                    loopRecords(data);
                }
            }
        }

        function handleGroups(groups) {
            for (var i = 0; i < groups.length; i++) {
                var gr = groups[i];
                offsetDateFields(gr); //handle the Key variable as well
                if (gr.HasSubgroups) {
                    handleGroups(gr.Items)
                } else {
                    loopRecords(gr.Items);
                }
            }
        }

        function loopRecords(persons) {
            for (var i = 0; i < persons.length; i++) {
                var person = persons[i];
                offsetDateFields(person);
            }
        }

        function UTCToLocal(utcDate) {
            var offset = new Date().getTimezoneOffset() / 60;
            var date = new Date(utcDate);
            var hours = date.getHours();
            date.setHours(hours - offset);
            return date;
        }

        function offsetDateFields(obj) {
            for (var name in obj) {
                var prop = obj[name];
                if (typeof (prop) === "string" && prop.indexOf("/Date(") == 0) {
                    obj[name] = prop.replace(/-?\d+/, function (n) {
                        var offsetMiliseconds = (new Date(parseInt(n)).getTimezoneOffset()-8*60) * 60000;
                        return parseInt(n) + offsetMiliseconds
                    });
                }
            }
        }
    </script>