How do I format a Microsoft JSON date?

Learn how do i format a microsoft json date? with practical examples, diagrams, and best practices. Covers jquery, asp.net, ajax development techniques with visual explanations.

Decoding Microsoft JSON Dates: A Comprehensive Guide

Hero image for How do I format a Microsoft JSON date?

Learn how to parse and format the unique date string format returned by Microsoft services in JSON, commonly seen in ASP.NET Web API and WCF.

When working with web services, especially those built on Microsoft technologies like ASP.NET Web API or WCF, you might encounter a peculiar date format in JSON responses. Instead of standard ISO 8601 or Unix timestamps, dates often appear as /Date(1234567890000)/ or /Date(1234567890000-0500)/. This format, while non-standard, is easily parsable once you understand its structure. This article will guide you through understanding, parsing, and formatting these Microsoft JSON dates using JavaScript and jQuery.

Understanding the Microsoft JSON Date Format

The Microsoft JSON date format is essentially a wrapper around a Unix timestamp (milliseconds since January 1, 1970, UTC), optionally followed by a timezone offset. The format is "/Date(milliseconds)/" or "/Date(milliseconds+offset)/" (for positive offsets) or "/Date(milliseconds-offset)/" (for negative offsets). The offset is in the format HHMM.

flowchart TD
    A["Microsoft JSON Date String"]
    B{"Contains '/Date(' and ')/'"}
    C["Extract Content: 'milliseconds' or 'milliseconds+/-offset'"]
    D{"Content contains '+' or '-'"}
    E["Parse 'milliseconds' as Number"]
    F["Parse 'offset' as String"]
    G["Create Date Object with 'milliseconds'"]
    H["Apply 'offset' to Date Object"]
    I["Formatted Date Object"]

    A --> B
    B -- Yes --> C
    B -- No --> J["Invalid Format"]
    C --> D
    D -- No --> E
    E --> G
    D -- Yes --> E
    D -- Yes --> F
    F --> H
    G --> H
    H --> I

Flowchart for parsing Microsoft JSON date strings

The key is to extract the numeric part (milliseconds and optional offset) from within the "/Date(...)/" wrapper. Once you have the milliseconds, you can create a standard JavaScript Date object.

Parsing Microsoft JSON Dates with JavaScript

The most straightforward way to parse these dates in JavaScript is to use regular expressions to extract the numeric value and then pass it to the Date constructor. If a timezone offset is present, you'll need to handle it separately.

function parseMicrosoftJsonDate(jsonDate) {
    const match = /\/Date\((\d+)([+-]\d{4})?\)\/\.exec(jsonDate);
    if (match) {
        const milliseconds = parseInt(match[1], 10);
        const offset = match[2]; // e.g., "-0500"

        if (offset) {
            // Handle timezone offset if present
            // Note: JavaScript Date objects handle UTC internally.
            // If you want a date object representing the *local* time
            // at that offset, you'd need more complex logic.
            // For simplicity, we'll just create a UTC date from milliseconds.
            return new Date(milliseconds);
        } else {
            return new Date(milliseconds);
        }
    }
    return null; // Or throw an error for invalid format
}

// Example usage:
const date1 = parseMicrosoftJsonDate("/Date(1234567890000)/");
console.log(date1); // Outputs: Thu Feb 12 2009 19:31:30 GMT-0500 (Eastern Standard Time)

const date2 = parseMicrosoftJsonDate("/Date(1234567890000-0500)/");
console.log(date2); // Outputs: Thu Feb 12 2009 19:31:30 GMT-0500 (Eastern Standard Time)

const date3 = parseMicrosoftJsonDate("/Date(1678886400000+0100)/"); // March 15, 2023 12:00:00 PM UTC+1
console.log(date3); // Outputs: Wed Mar 15 2023 07:00:00 GMT-0400 (Eastern Daylight Time) (or similar local time)

JavaScript function to parse Microsoft JSON dates.

Integrating with jQuery and AJAX

When fetching data via AJAX with jQuery, you'll typically receive the JSON response as a string. jQuery's $.ajax function often automatically parses JSON strings into JavaScript objects. However, the date strings will remain as strings. You'll need to iterate through your data and apply the parsing function.

$.ajax({
    url: '/api/data',
    method: 'GET',
    dataType: 'json',
    success: function(data) {
        // Assuming 'data' is an array of objects, each with a 'CreatedDate' property
        data.forEach(function(item) {
            if (item.CreatedDate && typeof item.CreatedDate === 'string' && item.CreatedDate.startsWith('/Date(')) {
                item.CreatedDate = parseMicrosoftJsonDate(item.CreatedDate);
            }
        });
        console.log('Processed Data:', data);
        // Now 'data' contains actual Date objects
    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.error('AJAX Error:', textStatus, errorThrown);
    }
});

// Re-using the parseMicrosoftJsonDate function from above
function parseMicrosoftJsonDate(jsonDate) {
    const match = /\/Date\((\d+)([+-]\d{4})?\)\/\.exec(jsonDate);
    if (match) {
        const milliseconds = parseInt(match[1], 10);
        return new Date(milliseconds);
    }
    return null;
}

Example of parsing Microsoft JSON dates after an AJAX call with jQuery.

Formatting the Date for Display

Once you have a standard JavaScript Date object, you can format it for display using various methods. Modern JavaScript offers toLocaleDateString(), toLocaleTimeString(), and toLocaleString() for locale-aware formatting. For more advanced or custom formatting, external libraries are often preferred.

Native JavaScript

const myDate = new Date(1234567890000);

// Basic formatting console.log(myDate.toDateString()); // e.g., "Thu Feb 12 2009" console.log(myDate.toTimeString()); // e.g., "19:31:30 GMT-0500 (Eastern Standard Time)"

// Locale-aware formatting console.log(myDate.toLocaleDateString('en-US')); // e.g., "2/12/2009" console.log(myDate.toLocaleTimeString('en-US')); // e.g., "7:31:30 PM" console.log(myDate.toLocaleString('en-US', { year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit' })); // e.g., "February 12, 2009, 07:31 PM"

Moment.js (Legacy)

// Requires Moment.js library //

const myDate = new Date(1234567890000);

console.log(moment(myDate).format('MMMM Do YYYY, h:mm:ss a')); // February 12th 2009, 7:31:30 pm console.log(moment(myDate).format('YYYY-MM-DD HH:mm')); // 2009-02-12 19:31

Luxon (Modern)

// Requires Luxon library // const { DateTime } = luxon;

const myDate = new Date(1234567890000);

const dt = DateTime.fromJSDate(myDate);

console.log(dt.toLocaleString(DateTime.DATETIME_FULL)); // February 12, 2009 at 7:31:30 PM EST console.log(dt.toFormat('yyyy-MM-dd HH:mm')); // 2009-02-12 19:31

Choosing the right formatting method depends on your project's requirements and whether you want to include external libraries. For simple, locale-aware formatting, native JavaScript methods are often sufficient.