0

I''m using EF to query the database using anonymous type.

here the code I use for EF

    public JsonResult OverdueEventsCustom()
    {
        var eventCustomOverdue = _eventCustomRepository.FindOverdueEventsCustom();
        return Json(eventCustomOverdue, JsonRequestBehavior.AllowGet);
    }


    public IQueryable<dynamic> FindOverdueEventsCustom()
    {
        DateTime dateTimeNow = DateTime.UtcNow;
        DateTime dateTomorrow = dateTimeNow.Date.AddDays(1);
        return db.EventCustoms.Where(x => x.DateTimeStart < dateTomorrow)
                    .Select(y => new { y.EventId, y.EventTitle, y.DateTimeStart});
    }

Inspecting using the debugger I see the properties is in this format

Date = {16/08/2012 00:00:00}

The resultfor the JSON is

[{
    "EventId": 1,
    "EventTitle": "Homework Math",
    "DateTimeStart": "\/Date(1345108269310)\/"
}, {
    "EventId": 4,
    "EventTitle": "Homework help with Annie",
    "DateTimeStart": "\/Date(1345108269310)\/"
}, {
    "EventId": 6,
    "EventTitle": "Physic laboratory",
    "DateTimeStart": "\/Date(1345108269310)\/"
}]

I need the the json in this format

"DateTimeStart": "(16/08/2012)"

Any idea what i'm doing wrong here? thanks for your help

Related articles

http://www.hanselman.com/blog/OnTheNightmareThatIsJSONDatesPlusJSONNETAndASPNETWebAPI.aspx

How do I format a Microsoft JSON date?

Community
  • 1
  • 1
GibboK
  • 71,848
  • 143
  • 435
  • 658
  • 1
    Why do you need the date in the format `"(16/08/2012)"` ? It's a limitation of the of the `JavaScriptSerializer` and there is no simple solution see: http://stackoverflow.com/questions/726334/asp-net-mvc-jsonresult-date-format. As an alternative solution you can use [Json.Net](http://james.newtonking.com/projects/json-net.aspx) for the json serilization. – nemesv Aug 16 '12 at 10:32

1 Answers1

1

"\/Date(1345108269310)\/" is the correct way to pass a Date to javascript. The way I see it, you have two options here:

If you do not explicitly need the value as a date, you could just pass a string to the JSON variable, containing the pretty-printed date. Something along the lines of:

DateTimeStart: String.Format("{0: dd-MM-yyyy}", myDate)

If you will still need to use the variable a a date in javascript (for calculations for example), the most consice and readably way would be to create a javascript function that converts said date into the pretty-printed string you want (I don't know if such a function already exists. It isn't too hard to create though:

function prettyDate(date) {

    return date.getDate() + "-" + date.getMonth() + "-" + date.getFullYear();

}

I would suggest passing it along as a string from you code behind, as it is more readable. But that only works if you do not need to use the date except for displaying.

Flater
  • 12,908
  • 4
  • 39
  • 62