Kendo Grid Automatically changing Timezone

12,118

Solution 1

This was my solution

on controller I did like this

DateTime time = DateTime.Now();

string x = time.ToString("MM/dd/yyyy hh:mm:ss tt");

On View

columns.Bound(p => p.x);

It is sortable also.

Solution 2

Since the dates are created on the client when the response from the server is returned - the dates are always created with an offset according to the timezone of the browser

This will help you:

http://www.kendoui.com/code-library/mvc/grid/using-utc-time-on-both-client-and-server-sides.aspx

Solution 3

For example your client machine is in Sydney and your code is deployed in India

Saving datetime to DB: While passing the date time from client side(javascript) to server(.net) pass it as string, so that it won't get converted to server's time(UK) while saving into DB

If your datetime field is non editable then follow solution 1 otherwise solution 2 would be the right choice

Retrieving from DB:

Solution 1:

Client side Code:

cols.Bound(c => c.ExamDate).ClientTemplate(("#= ExamDateString #")).Hidden(false).Filterable(x => x.Cell(cell => cell.ShowOperators(false).Operator(StringOperator.eq.ToString())));

Server Side Code:

Server Model property for format

public string ExamDateString 
    { 
        get 
        { 
        return ExamDate.HasValue ? ExamDate.Value.ToString("dd/MM/yyyy hh:mm:ss") : string.Empty; 
        } 
    }

Solution 2:

Retrieving from DB:

Client side code:

$.ajax({ 

            type: "POST", 

            url: '@Url.Action("Controller action method name", "Controller name")', 

            data: { "clientMachineTimeZoneOffsetInMinutes ": (new Date()).getTimezoneOffset() }, 

                success: function (data) { 

                    } 

         });

Server side code:

//Server Timezone(India) Offset minutes : 330

//Client Timezone(Sydney) Offset minutes : -600

//Difference between Client and Server timezone offset minutes = -270

var serverTimeZoneOffsetInMinutes = DateTimeOffset.Now.Offset.TotalMinutes;
var serverAndClientMachineTimeZoneDifferenceInMinutes = clientMachineTimeZoneOffsetInMinutes + serverTimeZoneOffsetInMinutes; 

//Update your date time field with this offset minutes
ExamDate = ExamDate.Value.AddMinutes(serverAndClientMachineTimeZoneDifferenceInMinutes);

Solution 3:
Solution 2 won't handle daylight saving scenario, This would be the ideal solution to handle all the scenario.

Before you return the DataSource result from the controller action method to kendo grid, do the below operation it would stop the conversion

       var response = new ContentResult
        {
            Content = JsonConvert.SerializeObject(value, new JsonSerializerSettings
            {
                DateTimeZoneHandling = DateTimeZoneHandling.Local,
                DateFormatString = "yyyy-MM-ddTHH:mm:ss"
            }),
            ContentType = "application/json"
        };

        return response;

Solution 4

Solution 2 in my above answer, daylight saving hour is getting added if you are not in daylight saving period but you are trying to access the date which falls in daylight saving period, rewriting the solution 2 to support daylight saving period aswell

Client side code to update timezone name:

    $.ajax({
            type: "POST",
            url: '@Url.Action("Controller action method name", "Controller name")',
            data: { "timeZoneName": Intl.DateTimeFormat().resolvedOptions().timeZone },
            success: function (data) {
                    }
            });

Controller method name to update the timezone in session:

   public ActionResult actionMethod(string timeZoneName)
    {
        Session["timeZoneName"] = Convert.ToString(timeZoneName);
        return Json(new { success = true });
    }

App config app setting entries:

<add key ="Europe/London"  value ="GMT Standard Time" />

Here the key is client time zone name returned by browser and maintained in session here, we have to add entries for all time zone

Place the below code in the controller action method to get the exam date:

var clientMachineTimeZoneName = Convert.ToString(Session["timeZoneName"]);

Get the sever timezone id from config for the corresponding time zone which we got from client side
var timeZoneId = ConfigurationManager.AppSettings[clientMachineTimeZoneName];

TimeZoneInfo clientTimezoneDetails = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);

var clientTimeZoneOffsetMinutes = clientTimezoneDetails.GetUtcOffset(x.ExamDate.Value).TotalMinutes * -1;
var serverAndClientMachineTimeZoneDifferenceInMinutes = clientTimeZoneOffsetMinutes + TimeZoneInfo.Local.GetUtcOffset(x.ExamDate.Value).TotalMinutes;

//Update your date time field with this offset minutes
ExamDate = ExamDate.Value.AddMinutes(serverAndClientMachineTimeZoneDifferenceInMinutes);

Solution 5

Another option is to use custom JsonResult and convert the date to ISO format.

public class IsoDateJsonResult : JsonResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }

        HttpResponseBase response = context.HttpContext.Response;

        if (!String.IsNullOrEmpty(ContentType))
        {
            response.ContentType = ContentType;
        }
        else
        {
            response.ContentType = "application/json";
        }
        if (ContentEncoding != null)
        {
            response.ContentEncoding = ContentEncoding;
        }
        if (Data != null)
        {
            var isoConvert = new IsoDateTimeConverter();
            response.Write(JsonConvert.SerializeObject(Data, isoConvert));
        }
    }

Then change your Controller method to return IsoDateJsonResult instead of ActionResult/JsonResult.

Share:
12,118

Related videos on Youtube

Raju S Nair
Author by

Raju S Nair

Interested in Asp.Net, Asp.Net MVC, Razor MVC, Kendo MVC, DevExpress MVC WCF, TFS, MS Build, Entity Framework, Jquery, LINQ, Android, PHP

Updated on June 13, 2022

Comments

  • Raju S Nair
    Raju S Nair almost 2 years

    On my Kendo Grid I recieve date time from server. On the client end, this time is changed to client's timezone and that is displayed. How can I show the same time from the server to the client.

    the following is my kendo code for binding the datetime.

    columns.Bound(p => p.CreateDate).Format("{0:dd/MM/yyyy hh:mm:ss}").Sortable(true).Width(180);
    
  • HaBo
    HaBo over 10 years
    This is fine in this scenario but not a right solution for all scenarios, lets say I have a Date of birth field hypothetical 1/1/1970 or 12/31/1970 when you change it to UTC to store it will change the date and retrieving again in UTC will also not work. Wondering if Kendo dont' have a fix/workaround on this.
  • Stuart Hallows
    Stuart Hallows about 10 years
    Bear in mind that in this case filtering with the date picker control will not work though.
  • ataravati
    ataravati about 8 years
    Did you mean columns.Bound(p => p.x);?
  • Mourya
    Mourya about 3 years
    Also the field is not editable by using this approach

Related