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
}
}
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With