I am getting JSON result from server, with date as given below
/Date(1224043200000)/
now I want to convert it into valid date format like dd/MM/yyyy (25/09/2017), so how can I convert JSON date into valid date format using javascript or jquery?
With the help of javascript create a function like below and pass the above JSON date ( /Date(1224043200000)/ ) to convert it into mm/DD/yyyy
function JavascriptDate(value) {
var pattern = /Date\(([^)]+)\)/;
var results = pattern.exec(value);
var dt = new Date(parseFloat(results[1]));
// get date in dd/MM/yyyy format
return (dt.getDate()+ "/"+ (dt.getMonth() + 1) + "/" + dt.getFullYear());
}
You can use Regex to convert JSON date into string using the javascript code below
var dateRegex = /^\/Date\((d|-|.*)\)[\/|\\]$/;
function convertWCFStringDate(strDate) {
var matched = dateRegex.exec(strDate);
if (matched) {
var parts = matched[1].split(/[-+,.]/);
return new Date(parts[0] ? +parts[0] : 0 - +parts[1]);
}
}
OR Another Solution can be simply using this code
function parseJsonDate(jsonDateString){
return new Date(parseInt(jsonDateString.replace('/Date(', '')));
}
Easy and simple solution, is to convert your DateTime into string before returning JSON
var StringDatetim = DateObject.ToString("dd/MM/yyyy");
OR
You can create a custom JSONResult class and override the ExecuteResult method, which will convert your results before sending it back to client side
Here is the Sample Class, which uses JSON.NET to serialize.
public class CustomJsonResult : JsonResult
{
private const string _dateFormat = "dd/MM/yyyy hh:mm:ss";
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
HttpResponseBase response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType))
{
response.ContentType = ContentType;
}
else
{
response.ContentType = "application/json";
}
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data != null)
{
// Using Json.NET serializer
var isoConvert = new IsoDateTimeConverter();
isoConvert.DateTimeFormat = _dateFormat;
response.Write(JsonConvert.SerializeObject(Data, isoConvert));
}
}
}
and you can use it as below
public ActionResult Index() {
return new CustomJsonResult { Data = new { DataList=db.TableName.ToList(); } };
}
You can also try below javascript code to get date from Microsoft JSON date string
var myDate = "/Date(1224043200000)/";
var value = new Date
(
parseInt(myDate.replace(/(^.*\()|([+-].*$)/g, ''))
);
var dat = value.getMonth() +
1 +
"/" +
value.getDate() +
"/" +
value.getFullYear();
console.log(dat);
Output:
"10/15/2008"
Thanks
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly