Javascript

ASPNET MVC JsonResult Date Format

19 September 2026 · 11 min read

ASPNET MVC JsonResult Date Format

Working with dates in ASP.NET MVC applications, especially when serializing data into JSON format using JsonResult, can sometimes present challenges related to date formatting. Often, developers encounter issues where dates are displayed in unexpected formats on the client-side. This can lead to confusion and require extra client-side code to parse and reformat the date. Understanding how to properly format dates when using JsonResult is crucial for creating seamless and user-friendly web applications. This article provides a comprehensive guide on mastering the ASP.NET MVC JsonResult Date Format, ensuring your dates are consistently displayed in your desired format, enhancing the overall user experience and streamlining your development process. We’ll cover various techniques, from using the DataContractJsonSerializer to leveraging custom converters, to achieve precise control over date serialization.

Understanding the Default JsonResult Date Format

By default, ASP.NET MVC’s JsonResult serializes dates into a format that can be less than ideal for direct consumption by JavaScript clients. Often, dates are serialized as a Microsoft-specific format that represents the number of milliseconds since the Unix epoch (January 1, 1970). This format, while technically correct, isn’t human-readable and requires parsing on the client-side to be displayed properly. For example, a date might appear as “/Date(1678886400000)/”. This is where understanding how to customize the date format becomes essential. Properly formatting dates server-side reduces the amount of client-side scripting needed, leading to cleaner and more maintainable code.

The default serialization behavior stems from the underlying JavaScriptSerializer class used by JsonResult. This class is configured by default to use the aforementioned millisecond-based format. While this format is precise, it lacks readability and requires extra processing on the client-side. To avoid this, developers often explore alternative serialization methods or customize the existing serializer to produce more user-friendly date formats. Several approaches are available, each with its own advantages and disadvantages, which we will explore in detail throughout this article. Choosing the right approach depends on factors such as project requirements, desired level of control, and compatibility with existing code.

One common misconception is that the [DisplayFormat] attribute will automatically handle the date formatting when using JsonResult. While this attribute works well for displaying dates in views, it doesn’t directly affect the serialization process of JsonResult. Therefore, developers need to implement specific strategies to control the date format during JSON serialization. Ignoring this nuance can lead to unexpected results and require debugging to identify the root cause. Understanding the difference between display formatting and serialization formatting is crucial for achieving consistent date representations across your ASP.NET MVC application.

Customizing Date Formatting with DataContractJsonSerializer

One robust approach to controlling the ASP.NET MVC JsonResult Date Format is to leverage the DataContractJsonSerializer. This serializer offers more flexibility and control compared to the default JavaScriptSerializer. By using DataContractJsonSerializer, you can specify the desired date format using the DateTimeFormat property of the DataContractJsonSerializerSettings class. This allows you to serialize dates into a format such as “yyyy-MM-dd” or “MM/dd/yyyy”, which are more easily consumable by JavaScript clients. This method is particularly useful when you need a consistent date format across your entire application.

To implement this, you would first create a DataContractJsonSerializerSettings object and set its DateTimeFormat property to your desired format string. Then, you would create a DataContractJsonSerializer instance using these settings. Finally, you would serialize your object using this serializer and return the resulting JSON string. This approach offers a clean and centralized way to manage date formatting. For example, the following snippet demonstrates how to serialize a DateTime object to a specific format:

using System.Runtime.Serialization.Json; using System.IO; using System.Text; using System; public string SerializeToJson(object obj, string dateFormat) { DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings { DateTimeFormat = new DateTimeFormat(dateFormat) }; DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType(), settings); using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, obj); return Encoding.UTF8.GetString(ms.ToArray()); } } 

It’s important to note that using DataContractJsonSerializer requires you to decorate your data classes with attributes like [DataContract] and [DataMember]. This is because the DataContractJsonSerializer relies on these attributes to determine which properties should be serialized. Neglecting to add these attributes will result in properties being ignored during serialization. This approach enforces a more explicit contract between your C code and the JSON output, promoting better maintainability and reducing the risk of unexpected serialization behavior. According to Microsoft’s documentation on DataContractJsonSerializer, using data contracts provides a clear and well-defined structure for serialization. Learn more about Data Contract Serialization.

Leveraging Custom JsonConverters

Another powerful technique for controlling the ASP.NET MVC JsonResult Date Format is to create and use custom JsonConverter classes. JsonConverter classes allow you to intercept the serialization process for specific types, such as DateTime, and apply custom formatting logic. This approach offers a high degree of flexibility and is particularly useful when you need different date formats for different properties or scenarios. By implementing a custom JsonConverter, you can encapsulate your date formatting logic in a reusable class, making your code cleaner and more maintainable.

To create a custom JsonConverter, you need to inherit from the JsonConverter class and override the CanConvert, ReadJson, and WriteJson methods. The CanConvert method determines whether the converter can handle a given type. The ReadJson method is responsible for deserializing JSON into an object of the specified type, and the WriteJson method is responsible for serializing an object into JSON. For example, to create a custom converter that formats DateTime objects as “yyyy-MM-dd”, you would implement the WriteJson method as follows:

using Newtonsoft.Json; using System; public class CustomDateTimeConverter : JsonConverter { private readonly string _format; public CustomDateTimeConverter(string format) { _format = format; } public override bool CanConvert(Type objectType) { return objectType == typeof(DateTime); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue(((DateTime)value).ToString(_format)); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { return DateTime.ParseExact(reader.Value.ToString(), _format, null); } } 

Once you have created your custom JsonConverter, you can apply it to specific properties using the [JsonConverter] attribute. For example: [JsonConverter(typeof(CustomDateTimeConverter), “yyyy-MM-dd”)]. Alternatively, you can register the converter globally by adding it to the JsonSerializerSettings.Converters collection. This approach ensures that the converter is applied to all DateTime properties by default, unless overridden by a more specific converter. According to NewtonSoft documentation, JsonConverter provides powerful mechanisms to customize the JSON serialization process. More on custom converters here. The advantages of using custom converters include increased flexibility, reusability, and the ability to handle complex serialization scenarios. However, it also requires more code and a deeper understanding of the JSON serialization process.

Global Configuration of JsonResult Date Format

For applications where a consistent ASP.NET MVC JsonResult Date Format is required across all JsonResult responses, configuring the date format globally is the most efficient approach. This eliminates the need to specify the format for each individual action or property. By modifying the global JSON serializer settings, you can ensure that all dates are serialized according to your desired format without any additional effort. This centralized approach simplifies maintenance and ensures consistency throughout your application.

To configure the date format globally, you can modify the JsonSerializerSettings in the Application_Start method of your Global.asax.cs file. This method is executed when the application starts, allowing you to set up global configurations. Within this method, you can access the JsonSerializerSettings and set the DateFormatString property to your desired format. For example:

protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); var jsonSettings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings; jsonSettings.DateFormatString = "yyyy-MM-ddTHH:mm:ssZ"; } 

This configuration ensures that all JsonResult responses will serialize dates using the “yyyy-MM-ddTHH:mm:ssZ” format, which is compatible with ISO 8601. You can adjust the DateFormatString property to any valid date format string that meets your specific requirements. Ensure that the format string is compatible with both the server-side serialization and the client-side parsing to avoid any discrepancies. Another approach could be to register a custom JsonConverter globally, which provides even more flexibility in handling date serialization. Remember to restart your application after making these changes for the new settings to take effect. Learn about related topics.

  • Global configuration ensures consistency.
  • Easily maintainable and scalable.
Infographic here: Visual representation of date formatting options.
FAQ: ASP.NET MVC JsonResult Date Format ---------------------------------------
Q: Why are my dates showing up as "/Date(1234567890)/" in my JsonResult?
A: This is the default date format used by the JavaScriptSerializer. It represents the number of milliseconds since the Unix epoch. You need to customize the date format using the techniques described in this article.
Q: How do I apply a custom date format to a specific property?
A: Use the \[JsonConverter\] attribute on the property and specify your custom JsonConverter class.
Q: Can I use the \[DisplayFormat\] attribute to format dates in JsonResult?
A: No, the \[DisplayFormat\] attribute only affects how dates are displayed in views, not how they are serialized in JsonResult.
Q: What is the best approach for globally configuring the date format?
A: Modify the JsonSerializerSettings in the Application\_Start method of your Global.asax.cs file.
To summarize, formatting dates correctly in your ASP.NET MVC JsonResult responses is essential for ensuring a smooth user experience. We've explored several methods, including using the DataContractJsonSerializer, creating custom JsonConverter classes, and configuring the date format globally. Each approach has its own strengths and is suitable for different scenarios. By understanding these techniques, you can effectively control the ASP.NET MVC JsonResult Date Format and ensure that your dates are consistently displayed in your desired format, regardless of the client-side technology used. Remember that choosing the right method depends on your specific requirements, project size, and desired level of control.

Take the next step in enhancing your ASP.NET MVC applications. Experiment with the different date formatting techniques discussed in this article and choose the one that best suits your needs. Consider exploring advanced JSON serialization options for even greater control. By mastering date formatting, you’ll improve the usability and maintainability of your applications, leading to a better overall experience for both developers and users. The consistent presentation of data, including dates, helps build trust and credibility with your users, demonstrating attention to detail and a commitment to quality. Happy coding!

  • Consider exploring advanced JSON serialization options for even greater control.
  • Improve usability and maintainability of your applications.
  1. Define the desired date format.
  2. Implement the chosen formatting technique.
  3. Test the output to verify the format.

Question & Answer :
I have a controller action that effectively simply returns a JsonResult of my model. So, in my method I have something like the following:

return new JsonResult(myModel); 

This works well, except for one problem. There is a date property in the model and this appears to be returned in the Json result like so:

"\/Date(1239018869048)\/" 

How should I be dealing with dates so they are returned in the format I require? Or how do I handle this format above in script?

Just to expand on casperOne’s answer.

The JSON spec does not account for Date values. MS had to make a call, and the path they chose was to exploit a little trick in the javascript representation of strings: the string literal “/” is the same as “\/”, and a string literal will never get serialized to “\/” (even “\/” must be mapped to “\\/”).

See http://msdn.microsoft.com/en-us/library/bb299886.aspx#intro_to_json_topic2 for a better explanation (scroll down to “From JavaScript Literals to JSON”)

One of the sore points of JSON is the lack of a date/time literal. Many people are surprised and disappointed to learn this when they first encounter JSON. The simple explanation (consoling or not) for the absence of a date/time literal is that JavaScript never had one either: The support for date and time values in JavaScript is entirely provided through the Date object. Most applications using JSON as a data format, therefore, generally tend to use either a string or a number to express date and time values. If a string is used, you can generally expect it to be in the ISO 8601 format. If a number is used, instead, then the value is usually taken to mean the number of milliseconds in Universal Coordinated Time (UTC) since epoch, where epoch is defined as midnight January 1, 1970 (UTC). Again, this is a mere convention and not part of the JSON standard. If you are exchanging data with another application, you will need to check its documentation to see how it encodes date and time values within a JSON literal. For example, Microsoft’s ASP.NET AJAX uses neither of the described conventions. Rather, it encodes .NET DateTime values as a JSON string, where the content of the string is /Date(ticks)/ and where ticks represents milliseconds since epoch (UTC). So November 29, 1989, 4:55:30 AM, in UTC is encoded as “\/Date(628318530718)\/”.

A solution would be to just parse it out:

value = new Date(parseInt(value.replace("/Date(", "").replace(")/",""), 10)); 

However I’ve heard that there is a setting somewhere to get the serializer to output DateTime objects with the new Date(xxx) syntax. I’ll try to dig that out.


The second parameter of JSON.parse() accepts a reviver function where prescribes how the value originally produced by, before being returned.

Here is an example for date:

var parsed = JSON.parse(data, function(key, value) { if (typeof value === 'string') { var d = /\/Date\((\d*)\)\//.exec(value); return (d) ? new Date(+d[1]) : value; } return value; }); 

See the docs of JSON.parse()