I have a controller action that effectively simply returns a JsonResult of my model. So, in my method I have something like the following:
return new JsonRes
Not the most elegant way but this worked for me:
var ms = date.substring(6, date.length - 2);
var newDate = formatDate(ms);
function formatDate(ms) {
var date = new Date(parseInt(ms));
var hour = date.getHours();
var mins = date.getMinutes() + '';
var time = "AM";
// find time
if (hour >= 12) {
time = "PM";
}
// fix hours format
if (hour > 12) {
hour -= 12;
}
else if (hour == 0) {
hour = 12;
}
// fix minutes format
if (mins.length == 1) {
mins = "0" + mins;
}
// return formatted date time string
return date.getMonth() + 1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + hour + ":" + mins + " " + time;
}
You can use this method:
String.prototype.jsonToDate = function(){
try{
var date;
eval(("date = new " + this).replace(/\//g,''));
return date;
}
catch(e){
return new Date(0);
}
};
I found this to be the easiest way to change it server side.
using System.Collections.Generic;
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
namespace Website
{
/// <summary>
/// This is like MVC5's JsonResult but it uses CamelCase and date formatting.
/// </summary>
public class MyJsonResult : ContentResult
{
private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Converters = new List<JsonConverter> { new StringEnumConverter() }
};
public FindersJsonResult(object obj)
{
this.Content = JsonConvert.SerializeObject(obj, Settings);
this.ContentType = "application/json";
}
}
}
Moment.js is an extensive datetime library that also supports this. http://momentjs.com/docs/#/parsing/asp-net-json-dates/
ex: moment("/Date(1198908717056-0700)/")
It might help. plunker output
See this thread:
http://forums.asp.net/p/1038457/1441866.aspx#1441866
Basically, while the Date()
format is valid javascript, it is NOT valid JSON (there is a difference). If you want the old format, you will probably have to create a facade and transform the value yourself, or find a way to get at the serializer for your type in the JsonResult
and have it use a custom format for dates.
0
In your cshtml,
<tr ng-repeat="value in Results">
<td>{{value.FileReceivedOn | mydate | date : 'dd-MM-yyyy'}} </td>
</tr>
In Your JS File, maybe app.js,
Outside of app.controller, add the below filter.
Here the "mydate" is the function which you are calling for parsing the date. Here the "app" is the variable which contains the angular.module
app.filter("mydate", function () {
var re = /\/Date\(([0-9]*)\)\//;
return function (x) {
var m = x.match(re);
if (m) return new Date(parseInt(m[1]));
else return null;
};
});