Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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     
                        }
                    }
                });
like image 769
Haseeb Akhtar Avatar asked Nov 14 '22 10:11

Haseeb Akhtar


1 Answers

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.

like image 195
Amar Palsapure Avatar answered Nov 16 '22 04:11

Amar Palsapure