Nish Rathi
Nish Rathi

Reputation: 254

Correct time not showing in json grid but the time is correct in MVC edit view

I have a JSON grid that displays email templates but the problem is that the last change date shown is ahead of current date but the same record last change date is shown correctly when editing that record in MVC Edit view.

The Date in Json Format Returned is : Date(1362686659073)

But on the Edit page for same record Date is: 3/7/2013 12:04:19 PM i.e. Date(1362638059000)

There is a difference of around 13.5 hours in the same date.

this is my Code returning the Data to JSON

        TemplateGridExt ext = new TemplateGridExt();
        ext.Count = client.GetPagedGridCountEmailTmpl(filter);
        ext.Data = result.EmailTmpl_Vs.ToList();
        return this.Json(ext, JsonRequestBehavior.AllowGet);

Upvotes: 0

Views: 149

Answers (1)

GSingh
GSingh

Reputation: 196

Try to pass the data in some other format like string, then it should work fine.

Try this code -

First create a class like this -

public class TimeFormatter : DateTimeConverterBase
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return DateTime.Parse(reader.Value.ToString());
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {

        writer.WriteValue(((DateTime)value).ToString("yyyy/MM/dd"));//format for date
    }
}

use this code to return the Json data to your view -

JsonSerializerSettings jSettings = new JsonSerializerSettings()
            {
                Formatting = Formatting.Indented,
                DateTimeZoneHandling = DateTimeZoneHandling.Utc
            };

            jSettings.Converters.Add(new TimeFormatter());
            JsonSerializer.Create(jSettings);


            return JsonConvert.SerializeObject(data, jSettings);//'data' is list of objects to return to view.

dont forget to include there namespaces -

using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

Upvotes: 1

Related Questions