Haseeb Akhtar
Haseeb Akhtar

Reputation: 1263

Return Json from MVC controller but Date format not proper in javascript

I am working in a project where I create a grid using data from database, in my controller I have this code

List<IEmployeeEntity> list = new Employee(connectionString).GetEmployeeRecord();

It returns me list of employees with some date and further I convert it to Json using return Json(list); But the date format I got in my java script grid like /Date(1325075075113)/ My javascript code is like

$.ajax({
        url: ../getRecord,
        type: 'POST',
        data: {},
        async: false,
        success: function (result) {
            if (result !== "") {
                       Create Grid     
                        }
                    }
                });

Upvotes: 6

Views: 7928

Answers (8)

Manish Kundu
Manish Kundu

Reputation: 145

It returns server side date format. You need to define your own function to change date format.

function jsonDateFormat(jsonServerDate) {

// Changed data format;
return (new Date(parseInt(jsonServerDate.substr(6)))).format("mm-dd-yyyy / h:MM tt");

};

Upvotes: 0

Haseeb Akhtar
Haseeb Akhtar

Reputation: 1263

I resolve my problem by following

List<IEmployeeEntity> list = new Employee(connectionString).GetEmployeeRecord(); 
        return Json(
          list.Select(
                  n => new { 
                  n.key1, 
                  AddedOn = n.AddedOn.Value.ToShortDateString() : String.Empty, 
                  n.key2, n.key3 
        }));

Upvotes: 0

NoWar
NoWar

Reputation: 37633

I have resolved this problem for myself in the following manner:

Just add to IEmployeeEntity 1 extra filed that will format this DateTime as you need and later use it on callback.

class IEmployeeEntity
{
   public DateTime StartDate {set; get;}

   public DateTime FormatedStartDate {  get  { return StartDate.ToString("MM/dd/yyyy") } }

}

So just use FormatedStartDate in your Javascript and you will get correct format.

or if you have some View Class you simply do

class IEmployeeEntity
{
   private DateTime startDate;
   public DateTime StartDate 
   { 
       set 
          { 
              startDate = value; 
          } 
       get { 
              return startDate.ToString("MM/dd/yyyy"); 
           } 
    }
}

Upvotes: 0

breathingdust
breathingdust

Reputation: 205

The JavascriptSerializer used by .Net produces that particular date format.

You can convert it to a JavaScript date with the following if you wish to format it client side:

var javascriptDate = new Date(parseInt(dateTimeInNetFormat.substr(6)))

Upvotes: 0

TwTw
TwTw

Reputation: 547

I done something like this in the this way :

put the grid into a -partial view . from your controler insted of return json return partial view :

  List<IEmployeeEntity> list = new Employee(connectionString).GetEmployeeRecord();
  return PartialView("GridPartial", list);

In your view : 1. use : @model IEnumerable. 2. add a div that contains the partial:

  <div id="partial">
     @Html.Partial("GridPartial", @model)         
  </div> 

and then in yout ajax :

$.ajax({
        url: ../getRecord,
        type: 'POST',
        data: {},
        async: false,
        success: function (result) {
               if (result.indexOf("<!DOCTYPE html>") == -1) {
                      $("#partial").empty();
                      $("#partial").html(result);
                  }
                    }
                });

in the partial view foreach in the model (yout list) and fill the Grid...

Upvotes: 0

Amar Palsapure
Amar Palsapure

Reputation: 9680

I had created two extension methods for such scenario

/// <summary>
/// Converts the value of the current System.DateTime object to its equivalent string representation using the specified format and culture-specific format information.
/// </summary>
/// <param name="date">DateTime instance</param>
/// <param name="format">A standard or custom date and time format string.</param>
/// <returns>A string representation of value of the current System.DateTime object as specified by format and provider.</returns>
public static string ToFormatString(this DateTime date, string format) {
    return date.ToString(format, new CultureInfo("en-US"));
}

/// <summary>
/// Returns the number of milliseconds since Jan 1, 1970 (useful for converting C# dates to JS dates)
/// </summary>
/// <param name="dt">Date Time</param>
/// <returns>Returns the number of milliseconds since Jan 1, 1970 (useful for converting C# dates to JS dates)</returns>
public static double UnixTicks(this DateTime dt) {
    DateTime d1 = new DateTime(1970, 1, 1);
    DateTime d2 = dt.ToUniversalTime();
    TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
    return ts.TotalMilliseconds;
}

You can choose any of them. To convert date to string you can simply do,

 var dateString = myDate.ToFormatString("dd/MM/yyyy");

You don't have to worry about the culture of the machine.

Hope this helps you.

Upvotes: 1

Pranay Rana
Pranay Rana

Reputation: 176886

its not javascript issue i think you need to formate you date in you code as you required i.e in C# code only.

somthing like below might help you ..

List<IEmployeeEntity> list = new Employee(connectionString).GetEmployeeRecord();
list.All(x => { x.mydate = x.mydate.ToString("dd/MM/yyyy"); return true; }) 

or

try this solution when your property is of type datetime because in first one it will give you an error if the property type is datetime

var q = from o in MyList
        select new { mydate   = x.mydate.ToString("dd/MM/yyyy"), 
                     prop1 = o.prop1, 
                     prop2 = o.prop2
                   };

Upvotes: 0

mehran
mehran

Reputation: 1466

Yes, it's server side (generation) issue. what's the type of date property in Employee entity. default behaviuor call its ToString() method.

Upvotes: 0

Related Questions