0

I am fetching datetime from SQL Server using Entity Framework. The format in my database is 2013-01-01 00:00:00.000 where as when I get it via Entity Framework in JSON format, it is "\\/Date(1356980400000+0500)\\/".

Here is my code

public class SurveyData
{       
        [DataMember]
        public DateTime? CreatedDate { get; set; } 
}

var surveyDataList = (from survey in context.FDT_SURVEY                             
                      where survey.Name == surveyName 
                      select new SurveyData
                          {
                              SurveyID = SqlFunctions.StringConvert((double)survey.SURVEY_ID).Trim(),
                              CreatedDate = survey.CREATED_DATE,
                          }
    );

in my database, the datatype of CREATED_DATE is datetime.

Unable to understand what is the issue. Any help !

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Ahmed
  • 814
  • 2
  • 19
  • 38
  • 1
    `DATETIME` in SQL Server is **not** stored in any string format - it's stored as an 8 byte datatype. SQL Server dates don't have any **format** associated with them by default. The date you're showing in JSON is the standard JSON encoding. So what's the problem with that?? – marc_s May 16 '13 at 11:27
  • 1
    \\/Date(1356980400000+0500)\\/ , I am receiving date time in this format. – Ahmed May 16 '13 at 14:22
  • Yes - again - what is the problem with that?? That is standard JSON - can you not convert it to a .NET object - or what's the problem?? – marc_s May 16 '13 at 14:26

2 Answers2

3

Try this:

    [DisplayFormat(DataFormatString = "{0,d}")]
    [DataType(DataType.DateTime)]
    public DateTime? CreatedDate { get; set; } 
Bappi Datta
  • 1,360
  • 8
  • 14
1

Entity Framework doesn't return anything in JSON format. It populates .NET objects with data, or populates databases with data from .NET objects. Attaching the debugger would show that the CreatedDate has the correct value in it, I believe.

The actual problem is more likely to do with the fact that JSON has no concept of a "date" or "datetime" type, despite the comments on the question. See The "right" JSON date format. Some serialization code is taking the .NET SurveyData class and serializing it to JSON using the .NET framework's JSON serializer (possibly the DataContractJsonSerializer) and this is writing it out in the format you are seeing. This might be WCF or else an older version of ASP.NET MVC or Web API.

Later versions of ASP.NET use the NewtonSoft JSON.net library to perform serialization of objects. By default these use the ISO 8601 format, which is what most of the world expects in a JSON object for a date or datetime field.

Community
  • 1
  • 1
Josh Gallagher
  • 5,211
  • 2
  • 33
  • 60