Formatting dates in a C# MVC application after parsing JSON

I am working on an MVC application that retrieves data from a SQL database and passes it to a view. One of the views contains a Kendo grid that displays the data, including a date column. The date data is stored in the SQL database as DateTime, while the model in the application uses the variable DateTime? When the data is passed to the view, the date column is formatted like this:

columns.Bound(sc => sc.RefundDate).Width(10).Title("Refund Date").Format("{0:MM/dd/yyyy}");

The displayed date format looks correct, for example, March 7, 2023, is displayed as 03/07/2023.

I am now setting up an AJAX call to the controller that triggers when a specific button is clicked. The AJAX call fetches new data and displays it in generic Kendo text boxes. I have a piece of JavaScript code that executes upon succeeding AJAX call:

function SetSmallClaimsDetails(data) {
    console.log(data);
    $("#SmallClaimsRefundDate").val(data.RefundDate);
}

When the code runs and I check the console log, I see:

Object
   ActualRefund: 0
   RefundDate: "/Date(1678206755990)/"

I suspect that the date is being converted by JSON. Here's the AJAX call code:

    var url = '/Case/GetSmallClaimsByRecordNumber?ID=789456';
    
    $.ajax({
        type: 'GET',
        url: url,
        dataType: 'text',
        success: function (data) {
            if (data != undefined) {
                var jsonData = JSON.parse(data);
                jsonData.ID = ID;
                SetSmallClaimsDetails(jsonData);
            }
        }
    });

If I modify my JavaScript to this:

function SetSmallClaimsDetails(data) {
    console.log(data);
    var date = new Date();
    if (!data.RefundDate) {
        date=''
    } else {
        date = new Date(parseInt(data.RefundDate.substr(6)));
    }
    $("#SmallClaimsRefundDate").val(date);
}

The display date changes to:

Tue Mar 07 2023 11:32:35 GMT-0500 (Eastern Standard Time)

How can I make the date display as 03/07/2023?

Appreciate any help. Thank you.

Answer №1

function DisplaySmallClaimsInfo(data) {
    console.log(data);
    var date = new Date(parseInt(data.ClaimDate.substr(6)));
    var formattedDate = date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: '2-digit' });
    $("#SmallClaimsClaimDate").val(formattedDate);
}

Make sure to refer to the resources provided, they can greatly assist with your queries.

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

Transformation of looks post a refresh

Initially, the CSS and appearance of the page look fine when I first open it (after clearing the cache). However, upon refreshing the page, a part of it changes (specifically, the padding direction of a div). This change occurs consistently with each refre ...

Transmit the standard information via an AJAX POST inquiry

I need to send a default data with each ajax post request, but the current code is sending the data for all requests. Can you provide some guidance on how to fix this issue? $.ajaxSetup({ data: { token: $('#token').attr(&a ...

Creating a View-Model for a header bar: A step-by-step guide

I am looking to develop a View-Model for the header bar using WebStorm, TypeScript, and Aurelia. In my directory, I have a file named header-bar.html with the following code: <template bindable="router"> <require from="_controls/clock"></ ...

Error encountered when attempting to add document to Firebase database: admin:1. An unexpected FirebaseError occurred, stating that the expected type was 'Na', but it was actually a custom object

I am encountering an error when trying to add a document to my collection in Firebase. I have successfully uploaded an image to Storage and obtained the URL, but this specific step is causing issues. I have followed the code implementation similar to how F ...

A helpful tip on incorporating Snack Bar Material UI within an if statement

When my Camera Component encounters an error, I want to display a snackbar notification. I attempted to encapsulate the component within a function and pass the error message as props, calling it in the if statement. However, this approach did not work as ...

Dealing with Sequelize Errors

After reviewing the code provided, I am curious if it would be sufficient to simply chain one .catch() onto the outermost sequelize task rather than attaching it to each individual task, which can create a cluttered appearance. Additionally, I am wonderin ...

Combining multiple template filters in ng-table with the power of CoffeeScript

Combining AngularJS, ng-table, and coffeescript has been quite a task for me. I've been trying to create a multiple template filter within coffeescript and pass it into my angularjs template. One of the challenges I'm facing is with a combined & ...

What is the best way to extract JSON data from an HTML file and store it into a Python

My goal is to extract structured data from a JSON statement embedded in an HTML page. To achieve this, I extracted the HTML content and obtained the JSON using XPath: json.loads(response.xpath('//*[@id="product"]/script[2]/text()').extract_first ...

Steps for converting an Mqtt5 payload back into JSON

Is there a way to convert the result from Mqtt5Publish.getPayloadAsBytes() into a JSON string that is properly formatted? For example, how can I take a message published in this format: '{"SampleData0": "1.2.3", "SampleData1& ...

Transforming the FormData() format into a jQuery structure

Hey there! I've been doing some research online about uploading files using JavaScript, and I stumbled upon some great resources, including this one https://developer.mozilla.org/en-US/docs/Web/API/FormData. I have a script that uploads an image to th ...

Ways to prompt for user input using JavaScript

How can I collect user input using JavaScript for a website that saves the input into a text file? Below is the code I am currently using: <button type="button" onclick="storeEmail()">Enter Email</button> <script> ...

Updating Angular components by consolidating multiple inputs and outputs into a unified configuration object

When I develop components, they often begin with numerous @Input and @Output properties. However, as I continue to add more properties, I find it beneficial to transition to utilizing a single config object as the input. For instance, consider a component ...

What could be causing the if statement to evaluate as false even though the div's style.display is set to 'block'?

Building a react application using createreactapp and encountering an issue with an if statement that checks the CSS display property of a div identified as step1: const step1 = document.getElementById("step-1") if (step1.style.display === 'blo ...

Creating a React table with customizable columns and rows using JSON data sources

My query is this: What is the most effective way to dynamically display header names along with their respective rows? Currently, I am employing a basic react table for this purpose. As indicated in the table (2017-8, 2017-9, ....), I have manually entere ...

"Using an empty array before each statement in jQuery Ajax to handle JSON data

I have a script using jQuery that gathers data from multiple websites and then saves it into a SQL database through AJAX and PHP. Right now, the script saves each set of collected data from a site individually. I would like to modify this so that the scrip ...

Is there a way to incorporate external HTML files into my webpage?

Looking to update an existing project that currently uses iFrames for loading external HTML files, which in this case are actually part of the same project and not from external sites. However, I've heard that using iFrames for this purpose is general ...

Creating a dynamic anchor scrolling effect within a dropdown select menu

Having trouble achieving smooth scrolling with a select option element, only works with a link. Any suggestions? Check out the jsfiddle demo to see what I mean! $(function() { $('a[href*=#]:not([href=#])').click(function() { if (location. ...

Using React Native to create a concise text component that fits perfectly within a flexbox with a

Within a row, there are two views with flex: 1 containing text. <View style={{ flexDirection: "row", padding: 5 }}> <View style={{ flex: 1 }}> <Text>Just a reallyyyyyyyy longgggg text</Text> </View> ...

What is the best way to make a CSS class appear in my javascript using the method I have been using before?

I am facing an issue in making this code work properly. It functions correctly for my caption element as there is only one caption tag in my HTML. However, the same code does not work for my TR element since it requires a for loop to iterate through multip ...

Decoding JSON responses using JavaScript

Below is an illustration of the JSON response: {testing:[ {"title":"Hello","text":"Hello Test!"}, {"title":"World","text":"World Test!"} ]} I am looking for a way to parse this JSON data using jQuery's getJSON and each function, in order to ...