How To Convert Date In Dd/Mm/Yyyy Format In Jquery

When working with dates in web applications, it’s often necessary to convert them to a specific format for display purposes. In this blog post, we will learn how to convert a date in JavaScript to the DD/MM/YYYY format using jQuery.

Step 1: Include jQuery in Your Project

First, make sure you have included the latest version of jQuery in your project. You can either download it from the official jQuery website or include it using a CDN like Google or Microsoft.

For this example, we will use the Google CDN. Add the following code to the head section of your HTML file:

<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script>

Step 2: Create a Function to Convert Date Format

Now let’s create a JavaScript function that will take a date object as an input and return the date in the DD/MM/YYYY format.

Add the following code to your JavaScript file or inside a <script> tag in your HTML file:

    function formatDate(date) {
        var day = date.getDate();
        var month = date.getMonth() + 1; //Months are zero-based
        var year = date.getFullYear();

        // Pad the day and month with leading zeros, if necessary
        day = (day &lt; 10) ? '0' + day : day;
        month = (month &lt; 10) ? '0' + month : month;

        return day + '/' + month + '/' + year;
    }
    

Step 3: Use the Function to Convert Date

Now that our formatDate function is ready, we can use it to convert any date object to the desired DD/MM/YYYY format.

For example, let’s assume we have a date input field with the ID “dateInput” and we want to display the selected date in the DD/MM/YYYY format in an element with the ID “formattedDate”.

Add the following code to your JavaScript file or inside a <script> tag in your HTML file:

    $(document).ready(function() {
        $('#dateInput').on('change', function() {
            var date = new Date($(this).val());
            var formattedDate = formatDate(date);
            $('#formattedDate').text(formattedDate);
        });
    });
    

With this code, whenever the user selects a date in the “dateInput” field, the formatDate function will be called, and the result will be displayed in the “formattedDate” element.

Conclusion

In this blog post, we’ve learned how to convert a date to the DD/MM/YYYY format using jQuery. This can be useful in a variety of web applications where you need to display dates in a specific format. Remember to include the jQuery library in your project and create a function to handle the date conversion. Happy coding!