mayank gupta
mayank gupta

Reputation: 511

Kendo Grid DateTime Column Shows Incorrect Date

I have a Kendo Grid which have a datetime columns, while fetching the date from database we are getting correct date but during display Date gets changed. For ex: DB date is 07/06/2017 but while display on website it gets changed into 06/06/2017, considering MM/DD/YYYY. Could anyone please help me on this. Our DB and Website both located in new york region.

Upvotes: 3

Views: 3670

Answers (1)

dimodi
dimodi

Reputation: 4139

The Kendo UI DataSource uses JavaScript Date objects for dates. These objects are always in the client's time zone, which may lead to changes in the date. A possible option is to use UTC dates:

http://docs.telerik.com/aspnet-mvc/helpers/grid/how-to/editing/utc-time-on-both-server-and-client


Edit, just copy the content of the link to here, because SO does not like the link the only answer

Use a ViewModel with a setter and a getter that explicitly set the DateTime Kind to UTC.

private DateTime birthDate;
public DateTime BirthDate
{
    get { return this.birthDate; }
    set {
        this.birthDate = new DateTime(value.Ticks, DateTimeKind.Utc);
    }
}

Use the requestEnd event of the DataSource to intercept and replace the incoming Date field with the time difference.

@(Html.Kendo().Grid<KendoUIMVC5.Models.Person>().Name("persons")
    .DataSource(dataSource => dataSource
        .Ajax()
        .Events(ev=>ev.RequestEnd("onRequestEnd"))
    )
    // ...
)

<script>
    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 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() * 60000;
                    return parseInt(n) + offsetMiliseconds
                });
            }
        }
    }
</script>

Upvotes: 4

Related Questions