I have a return of json
that comes from SqlServer
:
/Date(1386295200000)/
How to convert to date format dd/mm/yyyy
?
I have a return of json
that comes from SqlServer
:
/Date(1386295200000)/
How to convert to date format dd/mm/yyyy
?
The best option in this case is inherit the JsonResult
class and change the date format setting, as follows:
Class JsonResultDateFormat
:
public class JsonResultDateFormat : JsonResult
{
public JsonResultDateFormat(object data,
JsonRequestBehavior jsonRequestBehavior = JsonRequestBehavior.AllowGet)
{
Data = data;
JsonRequestBehavior = jsonRequestBehavior;
}
public override void ExecuteResult(ControllerContext context)
{
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = "application/json";
if (ContentEncoding != null) response.ContentEncoding = ContentEncoding;
JsonTextWriter writer = new JsonTextWriter(response.Output) {
Formatting = Formatting.Indented
};
JsonSerializer serializer = JsonSerializer.Create(new JsonSerializerSettings()
{
DateFormatString = "dd/MM/yyyy" // aqui o formato da data
});
serializer.Serialize(writer, Data);
writer.Flush();
}
public static JsonResultDateFormat Create(object data,
JsonRequestBehavior jsonRequestBehavior = JsonRequestBehavior.AllowGet)
=> new JsonResultDateFormat(data, jsonRequestBehavior);
}
and method Controller
:
public JsonResult Test()
{
using (DatabasecoreContext c = new DatabasecoreContext())
{
var data = c.Notice.ToList();
return JsonResultDateFormat.Create(data);
}
}
Your output is :
[
{
"Id": 1,
"CreditId": 1,
"Title": "Esporte",
"DateCreated": "01/02/2018"
},
{
"Id": 2,
"CreditId": 2,
"Title": "Esporte",
"DateCreated": "01/02/2018"
}
]
Reference Dealing with JSON Dates in ASP.NET MVC
I believe you are making a Json call and have a date field, just like Json below:
{
"rows":[
{
"UsuarioConviteID":1,
"Email":"[email protected]",
"Controle":"Aceito",
"DtControle":"\/Date(1518540878497)\/",
"DtCad":"\/Date(1518526866667)\/",
"Status":"A",
"Fixo":"Não"
}
],
"total":1
}
For you to convert date using JQuery you can use the function:
function formataData(value) {
if (value == null)
return null;
var dataTexto = value.replace('/', '').replace('/', '').replace('Date', '').replace('(', '').replace(')', '');
var date = new Date(parseInt(dataTexto));
return pad(2, date.getDate().toString(), '0') + "/" + pad(2, (date.getMonth() + 1).toString(), '0') + "/" + pad(4, date.getFullYear().toString(), '0');
};
The Momentjs
library already supports ASP.NET JSON Date
, see documentation .
Code sample:
moment("/Date(1386295200000)/").format("DD/MM/YYYY"); // 06/12/2013
moment("/Date(1198908717056-0700)/"); // Sat Dec 29 2007 04:11:57 GMT-0200
moment("/Date(1198908717056-0700)/").format("DD/MM/YYYY"); // 29/12/2007
See the result:
$(function() {
var result = moment('/Date(1386295200000)/').format("DD/MM/YYYY");
alert(result);
result = moment("/Date(1198908717056-0700)/");
alert(result);
result = moment("/Date(1198908717056-0700)/").format("DD/MM/YYYY");
alert(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.min.js"></script>
Or if you prefer in JSFiddle .
On the server side, the date is probably correct. Usually this happens in the conversion from DateTime
to Json
(and we usually treat the return in JavaScript
, I do not know if it's your case, the question does not address this).
If you want to make the adjustment only on the front-end side via javascript, create a function like this:
function ConverterJsonDateToJavascriptDate(data)
{
var retorno = new Date(parseInt(jsonDate.substr(6)));
}
Use this:
var jsonDate = "/Date(1386295200000)/";
var resultado = ConverterJsonDateToJavascriptDate(jsonDate);
I recommend using the MomentJS framework to handle dates. Here's an example from the Bootgrid documentation.
$("#grid").bootgrid({
converters: {
datetime: {
from: function (value) { return moment(value); },
to: function (value) { return value.format("lll"); }
}
}
});
Another alternative is to check the date output, using JsonProperty annotation:
using System;
using System.Web.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace WebApiDemo.Controllers
{
public class ValuesController : ApiController
{
// GET api/values
public IHttpActionResult Get()
{
var demo = new DemoViewModel { Data = DateTime.UtcNow };
return Ok(demo);
}
}
public class DemoViewModel
{
[JsonProperty(ItemConverterType = typeof(IsoDateTimeConverter))]
public DateTime Data { get; set; }
}
}