Extract the Date portion from a DateTime object in ASP.NET MVC

I am currently facing an issue with a property in my Model

[Display(Name = "День рождения")]
    [DataType(DataType.Date)]
    public System.DateTime Birthday { get; set; }

When trying to save the value to the database using AJAX, it is also writing the Time along with Date.

<script>
   $(document).ready(function () {
    $('#save').click(function () {
        save();
    });
});
    function save() {
        $.ajax({
            type: 'Post',
            dataType: 'Json',
            data: {
                FIO: $('#FIO').val(),
                Email: $('#Email').val(),
                Salary: $('#Salary').val(),
                Telephone: $('#Telephone').val(),
                English: $('#english').val(),
                City: $('#City').val(),
                Birthday: $('#Birthday').val(),
                id: $('#Interview_Id').val(),


            },
            url: '@Url.Action("WelcomeWriter", "Interwier")',
            success: function (da) {
                if (da.Result === "Success") {

                    window.location.href = da.RedirectUrl;

                } else {

                    alert('Error' + da.Message);
                }
            },
            error: function (da) {
                alert('Error');
            }
        });
    }

My goal is to only write the Date without the Time. How can I achieve this?

Answer №1

If you want to access Date functions in JavaScript, you can follow this example:

const inputDate = new Date($('#Birthday').val());

This will allow you to use methods like getDate(), getMonth(), and getFullYear().

For a complete date format, you can do the following:

const day = inputDate.getDate(); 
const month = inputDate.getMonth();  
const year = inputDate.getFullYear(); 
const fullDate = day + "/" + month + "/" + year;

Alternatively, you can also use:

const fullDate = inputDate.toLocaleDateString();

Answer №2

Ensure that you format the date correctly within your save() function prior to making the ajax request. Here is an example of how you can achieve this:

var d = new Date($('#Birthday').val());
var formattedBirthday = d.getFullYear() + "-" + ('0' + (d.getMonth() + 1)).slice(-2)
                + "-" + ('0' + d.getDate()).slice(-2);

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

I'm caught in a never-ending cycle as I navigate through sending information to my Python API and subsequently utilizing that information in the Next.js application to execute the Python script

I am encountering an issue with the response message, getting "Error sending data." The problem seems to arise when trying to retrieve data in server.py that is already specified in the code. For example, instead of using "msg_user", I should use ...

Tips for enhancing a search algorithm

I am currently working on implementing 4 dropdown multi-select filters in a row. My goal is to render these filters and update a new array with every selected option. Additionally, I need to toggle the 'selected' property in the current array of ...

Encountering a Jquery TypeError while trying to update the content on

I am currently working on a project where I aim to create a Java Spring application that functions as follows: upon receiving a GET request, the application sends an HTML page with a form. When the form button is clicked, a POST request containing XML cont ...

Accessing specific documents in Firebase cloud functions using a wildcard notation

Currently, I am working on implementing Firebase cloud functions and here are the tasks I need to achieve: Monitoring changes in documents within the 'public_posts' collection. Determining if a change involves switching the value of the &ap ...

JavaScript Error Caused by Newline Characters

I'm facing an issue with extracting data from a textbox using JavaScript. What I'm attempting to do is retrieve the value from a textbox, display it in an alert, and then copy it. Here's the current code snippet: var copyString = "Date: < ...

Ensure page is updated after an AJAX request in jQuery Mobile by refreshing the page

My jQueryMobile page structure in index.html looks like this: <div data-role="page"> <div data-role="header">...</div> <div data-role="content">...</div> <div data-role="footer">...</div> </div& ...

The Value Entered in Angular is Unsaved

I have encountered an issue with my app's table functionality. The user can enter information into an input field and save it, but upon refreshing the page, the field appears empty as if no data was entered. Can someone please review my code snippet b ...

Real-time filtering in personalized dropdown menu with search input

I have been attempting to create a custom list filter for input using a computed property. In one file, I am developing a widget, while in another file, I am implementing it. Below is the code snippet from the widget creation file: <template> ...

Embed your JavaScript code within the header tags of the WooCommerce order confirmation page

Seeking to enhance my thank you page with Google tracking script, I have developed code that successfully injects the tracker within the of the page, incorporating dynamic values. However, my goal is to embed it within the tags instead. function mv_goog ...

The function react.default.memo is not recognized at the createSvgIcon error

After updating my Material-UI version to 1.0.0, I encountered a peculiar error message stating that _react.default.memo is not a function at createSvgIcon Despite attempting to downgrade the react redux library to version 6.0.0 as suggested by some ...

Struggling to manage texbox with Reactjs

Currently working in Reactjs with Nextjs and encountering a problem with the "text box". When I use the "value" attribute in the textbox, I am unable to input anything, but when I use the "defaultValue" attribute, I receive a validation message saying "Ple ...

Trouble displaying MongoDB data on Meteor template

As I embarked on building my first app with Meteor, everything seemed to be going smoothly until I encountered an issue where a collection was no longer displaying in a template. Here is the code snippet: App.js Tasks = new Mongo.Collection("tasks"); i ...

Loading slides in bxSlider using ajax

Is there a method to dynamically insert a slide into bxSlider via ajax without affecting its smooth transition? I am looking to initially display the contents of only one slide upon page load, and then have subsequent slides loaded when the next or previo ...

Inject $scope into ng-click to access its properties and methods efficiently

While I know this question has been asked before, my situation is a bit unique. <div ng-repeat="hello in hello track by $index"> <div ng-click="data($index)"> {{data}} </div> </div> $scope.data = function($index) { $scope.sweet ...

What is the process for transferring ng-model values to a table in Angular?

My goal is to populate a table with JSON data using ng-repeat by clicking a button. I need to input either a first name or last name in order to display the results in the table. Is this the correct JavaScript function for achieving this? JavaScript Funct ...

Does the Width Toggle Animation fail to function in FireFox when using jQuery?

Has anyone else encountered this issue with the jQuery animate function not working in Firefox but working fine in IE8, Opera, and Chrome? I'm experiencing this problem and wondering if there's a workaround to make it work in Firefox as well. ht ...

What is the best way to eliminate special characters in an Ajax request?

I am looking to transmit images to the View using Ajax. On the Admin page with PHP, I upload multiple images. So, the image list will have a format like this: ["image_1.jpg","image_2.jpg","image_3.jpg"] I want to display the image list in div#res. It s ...

Improving the innerHTML syntax

I am looking for the correct syntax to add content to an element using innerHTML. Here is an example that isn't working as expected: openNewWindow: function(content) { popupWin = window.open(content, 'open_window', 'menubar, ...

Using Foreign Key in AJAX POST method with Django

I'm encountering difficulties with my web app as I try to specify a user in my Ajax request. Whenever I attempt to add a new item, an error pops up: TypeError: Field 'id' expected a number but got . Is there any solution to this issue? Her ...

Tips for creating a threaded commenting feature in Django

Currently, I am working on developing a commenting system using Django. Here's what I have accomplished so far: I have implemented AJAX initial comments where the parent comment is appended without requiring a page refresh and saved to the databas ...