Converting .NET DateTime to JSON and Handling Dates in JavaScript

Dec 01, 2025 · Programming · 24 views · 7.8

Keywords: .NET | DateTime | JSON | JavaScript | date conversion

Abstract: This article explores how to convert DateTime data returned by .NET services into JavaScript-friendly date formats. By analyzing the common /Date(milliseconds)/ format, it provides multiple parsing methods, including using JavaScript's Date object, regex extraction, and .NET-side preprocessing. It also discusses best practices and pitfalls in cross-platform date handling to ensure accurate time data exchange.

Introduction

In modern web development, data exchange between .NET backend services and JavaScript frontends is common, with date-time (DateTime) handling being particularly critical. When .NET serializes DateTime to JSON by default, it may produce formats like /Date(1245398693390)/, which requires special processing in JavaScript for correct parsing. This article delves into this conversion process, offering multiple solutions and analyzing their pros and cons.

JSON Serialization Format of .NET DateTime

The .NET framework (especially earlier versions) often uses a millisecond-based representation when serializing DateTime to JSON. For example, the number in /Date(1245398693390)/ represents milliseconds since January 1, 1970 (the Unix epoch). While compact, this format is not a standard JSON date format (like ISO 8601), necessitating additional parsing on the frontend.

Parsing Methods on the JavaScript Side

In JavaScript, the Date object can handle such millisecond timestamps. The best answer (Answer 1) provides two main approaches:

  1. Direct Use of Date Constructor: Extract the milliseconds and pass them to the Date object, e.g., var d = new Date(1245398693390);. This converts the timestamp to a date in the local timezone.
  2. Regex Extraction: Since the original string contains non-digit characters (like /Date( and )/), use a regular expression /-?\d+/ to match the numeric part, then parse: var m = re.exec(jsonDate); var d = new Date(parseInt(m[0]));. This method is more robust, handling negative timestamps (for dates before 1970).

For example, the following code demonstrates a complete parsing process:

var jsonDate = "/Date(1245398693390)/";
var re = /-?\d+/;
var match = re.exec(jsonDate);
if (match) {
    var milliseconds = parseInt(match[0], 10);
    var date = new Date(milliseconds);
    console.log(date.toLocaleString()); // Outputs formatted date
}

Preprocessing Solutions on the .NET Side

As a supplement, Answer 2 suggests preprocessing on the .NET side by converting DateTime to millisecond timestamps before returning. This can be implemented via an extension method:

public static class DateTimeExtensions
{
    public static double ToUnixMilliseconds(this DateTime dt)
    {
        DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        return (dt.ToUniversalTime() - epoch).TotalMilliseconds;
    }
}

After calling this method on the server, return the numeric value directly (e.g., 1245398693390), allowing the frontend to parse it with new Date(msg). This approach avoids string parsing overhead but requires proper timezone handling (using UTC).

Best Practices and Considerations

Conclusion

When converting .NET DateTime to JSON, developers can choose to parse the /Date(milliseconds)/ format on the JavaScript side or preprocess it into millisecond timestamps on the .NET side. The former is compatible with legacy systems, while the latter is more efficient. Regardless of the method, focusing on timezone and error handling is key. As technology evolves, adopting standard date formats (like ISO 8601) can simplify processes and improve interoperability.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.