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.
2
votes
Are you saying month and day are reversed or it changes 7/6/17 to 6/6/17?
– Steve Greene
no, While display it on website date get reduce by one. If date is 6th April then while display on website it is 5th April
– mayank gupta
What about the time? Does the time displayed is exactly like the time received from the server? If you're not displaying the time, display it as well since it could help you understand what the reason for the difference is.
– Shai
We need to show only date .. for that we are using Kendo.ToString(dateVar, /''mm/dd/yyyy'/); something like that
– mayank gupta
1 Answers
3
votes
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>