我正在尝试在dd-MM-yyyy
中显示日期,但我得到的日期始终采用以下格式:
2016-08-08T16:17:40.643
我正在使用asp.net mvc and returning data in json format
但是使用角度js显示此日期。
以下是我在Link尝试的答案,我将Perishable Dave和dav_i给出的答案合并:
public class JsonNetFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.Result is JsonResult == false)
{
return;
}
filterContext.Result = new JsonNetResult(
(JsonResult)filterContext.Result);
}
private class JsonNetResult : JsonResult
{
private const string _dateFormat = "dd-MM-yyyy";
public JsonNetResult(JsonResult jsonResult)
{
this.ContentEncoding = jsonResult.ContentEncoding;
this.ContentType = jsonResult.ContentType;
this.Data = jsonResult.Data;
this.JsonRequestBehavior = jsonResult.JsonRequestBehavior;
this.MaxJsonLength = jsonResult.MaxJsonLength;
this.RecursionLimit = jsonResult.RecursionLimit;
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
var isMethodGet = string.Equals(
context.HttpContext.Request.HttpMethod,
"GET",
StringComparison.OrdinalIgnoreCase);
if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet
&& isMethodGet)
{
throw new InvalidOperationException(
"GET not allowed! Change JsonRequestBehavior to AllowGet.");
}
var response = context.HttpContext.Response;
response.ContentType = string.IsNullOrEmpty(this.ContentType)
? "application/json"
: this.ContentType;
if (this.ContentEncoding != null)
{
response.ContentEncoding = this.ContentEncoding;
}
if (this.Data != null)
{
// Using Json.NET serializer
var isoConvert = new IsoDateTimeConverter();
isoConvert.DateTimeFormat = _dateFormat;
response.Write(JsonConvert.SerializeObject(this.Data));
}
}
}
}
[JsonNetFilter]
public ActionResult GetJson()
{
return Json(new { hello = new Date(2016-08-02 05:49:11.000) }, JsonRequestBehavior.AllowGet)
}
如何以dd-MM-yyyy
格式发送日期?
答案 0 :(得分:2)
您未将isoConvert
变量传递给JsonConvert.SerializeObject(this.Data)
,因此从未使用过。{p}您需要使用appropriate overload
SerializeObject
response.Write(JsonConvert.SerializeObject(this.Data, new [] { isoConvert } ));