JSON returning issue with date formatting

After converting a date to a string using ToString("d") in C# and then serializing it into JSON for the client, I'm encountering an issue where instead of displaying the formatted date on the page, I see the following literal text:

/Date(-62135575200000)/

I'm having trouble understanding why this is happening.

Answer №1

JSON and JavaScript do not provide date literals, resulting in various conventions being used. Microsoft's convention is considered "contrived" even by themselves as mentioned here.

If you need help decoding JSON dates, you can refer to this helpful question.

Answer №2

If you are dealing with dates in your code and need to convert values between different systems, such as passing dates back and forth in JavaScript, there are specific methods to handle this.

var d = new Date()
d.setTime(-62135575200000);
alert(d.toDateString());

You can refer to the discussion on Converting .NET DateTime to JSON for further insights and solutions provided by the community.

Below are two approaches mentioned for moving dates within the code:

 [WebMethod]
 public static DateTime loadDate()
 {
     return DateTime.Now;
 }
 [WebMethod]
 public static double loadDateTicks()
 {
     return DateTime.Now.UnixTicks();
 }
 public static class ExtensionMethods
 {
    // Calculate the number of milliseconds since Jan 1, 1970 (useful for converting C# dates to JS dates)
    public static double UnixTicks(this DateTime dt)
    {
        DateTime d1 = new DateTime(1970, 1, 1);
        DateTime d2 = dt.ToUniversalTime();
        TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
        return ts.TotalMilliseconds;
    }
 }

Credit is given to "Jeff Meatball Yang" for providing the extension method mentioned above.

For testing purposes, here is a sample frontend function:

function LoadDates() {
        $.ajax({
            url: "Default.aspx/loadDate",
            type: "POST",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            success: function (msg) {
                var re = /-?\d+/;
                var d = new Date(parseInt(re.exec(msg.d)[0]));
                alert(d.toDateString());
            },
            dataType: "json"
        });
        $.ajax({
            url: "Default.aspx/loadDateTicks",
            type: "POST",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            success: function (msg) {
                var dt = new Date(msg.d);
                alert(dt.toDateString());
            },
            dataType: "json"
        });
    }

Answer №3

If you want to format a date as mm/dd/yyyy, you can use the following code snippet: I encountered a similar problem and found a solution that worked for me:

var regexFormatDate = /-?\d+/;
var integerFormat = regexFormatDate.exec(message.data);
var dateObj = new Date(parseInt(integerFormat));
var formattedDate = dateObj.getMonth() + 1 + "/" + dateObj.getDate() + "/" + dateObj.getFullYear();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating an HTML structure that limits each li to only contain three div elements can be achieved using React and Underscore.js

To achieve this specific layout, I am looking to utilize only underscore.js functions. Below is the array that I have: var xyz = [{ 'name': 'test' },{ 'name': 'test1' },{ 'name': &ap ...

Tips for adding event listeners to dynamically-loaded content using AJAX

I need help with the following code snippet: $("#contantainer").load("some_page.txt"); Inside some_page.txt, I have the following content: <div class="nav"> <ul id="nav_ul"> <li><a class="nav_a" href="#home" id="home"> ...

Having trouble with the input range slider on Chrome? No worries, it's working perfectly fine

I'm currently facing an issue with an input range slider that controls the position of an audio track. It seems to work perfectly in Firefox, but in Chrome, the slider gets stuck and doesn't move when dragged. There is a function in place that up ...

Abbreviating AngularJS with JavaScript

While Angular offers the ng shortcut for directives in markup, I am curious about how to implement this in JavaScript code. For example, instead of writing angular.isArray, is it possible to use ng.isArray similar to jQuery ($) or Underscore (_)? ...

Is there a way to adjust the contrast of an image using an HTML slider and JavaScript without utilizing the canvas element?

Looking to develop a slider with HTML and JavaScript (or jQuery, CSV,...) that can adjust the contrast of an image, similar to this topic. However, I would prefer not to utilize Canvas in HTML5 for this project. Any suggestions on how to achieve this with ...

Tips for transferring data to an entry component in Angular 2 using ng-bootstrap modal

I've been grappling with sending data to a custom modal content component in Angular 2. My objective is to have the flexibility of calling this modal from any other component without duplicating code. Despite my efforts, including referencing the "Com ...

Retrieve the data entered in the submit button field

My question concerns a form with two buttons: <form method="post" action=""> <button type="submit" name="age" value="20">Age 20</button> <button type="submit" name="age" value="30">Age 30</button> </form> When ...

Linking two separate tables to a third shared table using a single foreign key in the C# language

In my project, I have three different classes: Item, Armor, and Weapon. The ITEM class serves as the parent class with generic properties, while ARMOR and WEAPON are specific subclasses that I want to connect to the item class. Below is a screenshot of m ...

How to open a PDF file in a new tab using Angular

Within my Angular 12 application, I am seeking to enable users to "view" a PDF file stored locally in the application within a new tab on Google Chrome. Currently, when implementing the code below in HTML, the file downloads rather than opening in a new ta ...

Troubleshooting problems with the CSS code for a progress bar in Gmail

I recently came across a unique progress bar design on Gmail and wanted to implement something similar. I found some code snippets on this webpage: . However, I encountered an issue where the progress bar was only displaying in Internet Explorer but not in ...

Can html-webpack-plugin be configured to create <style> elements from CSS files?

I am managing a static site with Vue and Webpack. In my project, I have a file named style.css containing global CSS rules which I import using import './styles.css' in my index.js file. Additionally, I have some .vue files that generate their o ...

Having trouble getting the toggleClass function to work properly?

I'm facing an issue with some straightforward code that I've written. $(function() { $("#tren").click(function() { $("#trens").toggleClass("show"); }); }); .show { color: "red"; } <ul> <li id="tren">Some text</li> < ...

Adding JSON data before the second to last element of an array:

I am looking to create a function that can consistently add JSON Items to an array just before the last item. const array = [ {India: { Score: '12', PlayedMatched: '21' } }, { China: { Score: '52', PlayedMatched: '51 ...

The use of Physijs and implementing setLinearVelocity for object movement

2-09-2015 - UPDATE: The code provided below is now functional with the use of setLinearVelocity(). If you were facing similar issues, this updated code may help you. Find the original question with the corrected code below... A player object has been deve ...

Populate a dropdown with values from a JSON object

There is a function in my code that retrieves JSON text from a specific website: window.onload = function httpGet() { var xmlHttp = null; var box = document.getElementById("http") //just for testing xmlHttp = new XMLHttpRequest(); xmlHttp. ...

Is the term 'Literal' in Javascript Arrays simply referring to its dynamic nature, allowing it to be modified at any time?

I'm confused why Mozilla refers to this as an Array 'Literal' when it's declared using the VARIABLE keyword and its content can be modified... var drinks = ["Espresso", "Latte", "Cappuccino"]; Could someone shed some light on this for ...

A guide to efficiently pre-rendering secure APIs on a server for Next.js

Currently, I am working on a project that involves fetching data from multiple pages. However, the challenge lies in the fact that all APIs are secured, except for the initial API that fetches data for the home page. Furthermore, all other APIs are protect ...

"Step-by-step guide on implementing a click event within a CellRenderer in Angular's Ag-Grid

paste your code hereI'm currently working on implementing edit and delete buttons within the same column for each row using Angular ag-Grid. To visually represent these buttons, I am utilizing icons. While I have successfully displayed the edit and de ...

Can someone guide me on how to extract checkbox values in a post method using Angular

I'm facing an issue with a table that contains a list of rules. Whenever the checkboxes are clicked, I want them to send a "true" value to an API endpoint. However, I keep receiving an error stating that the "associated_rule" is undefined. After tryi ...

unable to retrieve parent ID

I am having trouble retrieving the ID of the parent's parent of the event target. It keeps coming back as undefined, but I have verified through firebug that the ID does exist. Below is my HTML markup: <div class="grid-stack-item ui-draggable ui- ...