In MVC controllers, Newtonsoft. Json is often used to serialize objects into json strings and pass them to the front-end view. When an object has a DateTime type attribute, how can we convert the DateTime type to the desired format in the front and back ends?
There is a class with the DateTime type attribute:
using System;
namespace MvcApplication1.Models
{
public class Sample
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime Date { get; set; }
}
}
In the controller, Newtonsoft. Json is used to serialize the object instance into a json string:
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();
}
}
}
The foreground view uses a js file named "f" to convert the date format in json to the expected format:
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<p>
<span id="jsonDate">@ViewData["json"]</span>
</p>
<p>
The converted time format is: <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>
}
Result:
References:
Js files about "f": http://fisforformat.sourceforge.net/
About Newtonsoft. Json: http://james.newtonking.com/json/help/index.html? Topic = html/DatesInJSON.htm