MVC控制器中,经常使用Newtonsoft.Json把对象序列化成json字符串传递到前端视图。当对象中有DateTime类型的属性时,前后台如何处理才能把DateTime类型转换成想要的格式呢?
有这样的一个类具有DateTime类型属性:
using System; namespace MvcApplication1.Models { public class Sample
{ public int Id { get; set; }
public string Name { get; set; }
public DateTime Date { get; set; } }
}
控制器中使用Newtonsoft.Json把对象实例序列化成json字符串:
using System.Web.Mvc; using MvcApplication1.Models; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace MvcApplication1.Controllers { public class HomeController : Controller
{ public ActionResult Index() { var sample = new Sample() { Id = 1,
Name = "good", Date = DateTime.Now
};
JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc
};
ViewData["json"] = Newtonsoft.Json.JsonConvert.SerializeObject(sample, microsoftDateFormatSettings); return View(); }
}
}
前台视图使用一个叫"f"的js文件,把json中的日期格式转换成期望的样子:
@{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; }
<p>
<span id="jsonDate">@ViewData["json"]</span>
</p>
<p>
转换后的时间格式为:<span id="fDate"></span> </p>
@section scripts
{ <script src="~/Scripts/date.f-0.5.0.js"></script> <script type="text/javascript"> $(function () { var obj = $.parseJSON($('#jsonDate').text()); //$('#fDate').text(new Date(parseInt(obj.Date.substr(6))).f("yyyy-MM-dd HH:mm:ss")); $('#fDate').text(new Date(parseInt(obj.Date.substr(6))).f("yyyy-MM-dd"));
});
</script>
}
结果:

参考资料:
关于"f" 的js文件:http://fisforformat.sourceforge.net/
关于Newtonsoft.Json:http://james.newtonking.com/json/help/index.html?topic=html/DatesInJSON.htm