Jquery Moment js Convert String to Date Example

May 17, 2024 | jQuery


Hello Dev,

Greetings everyone! In this piece, we'll delve into the conversion of a string to a date using jQuery and Moment.js. We'll explore how Moment.js facilitates this conversion, particularly focusing on the format dd/mm/yyyy. Throughout, we'll examine how to utilize Moment.js' toDate() method to effortlessly convert a string into a date.

Read Also: How to Get Month Name from Month Number in Jquery Moment Js
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Jquery Moment js Convert String to Date Example -- ItErrorSolution.com</title>
    <!-- jQuery -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <!-- Moment.js -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
</head>
<body>
<input type="text" id="dateString" placeholder="Enter date in dd/MM/yyyy format">
<button onclick="convertDateString()">Convert</button>
<p id="dateObject"></p>
<p id="convertedDate"></p>

<script>
function convertDateString() {
    // Get the date string from the input field
    var dateString = $('#dateString').val();
    
    // Parse the date string using Moment.js
    var parsedDate = moment(dateString, "DD/MM/YYYY");
    
    // Convert the Moment.js object to a JavaScript Date object
    var dateObject = parsedDate.toDate();
    
    // Display the converted date
    $('#dateObject').text("Date Object: " + dateObject);
    $('#convertedDate').text("Converted Date: " + dateObject.toLocaleDateString());
}
</script>
</body>
</html>
Output:
Converted Date: 17/5/2024

Date Object: Fri May 17 2024 00:00:00 GMT+0530 (India Standard Time)

Thank you for your encouragement! If you have any questions or need further assistance, feel free to ask. I'm here to help!



Tags :
#jQuery
ItErrorSolution.com

ItErrorSolution.com

"Hey there! I'm a full-stack developer and proud owner of ItErrorSolution.com, based right here in India. I love nothing more than sharing handy tips and tricks with my fellow developers through easy-to-follow tutorials. When it comes to coding, I'm all about PHP, Laravel, Angular, Vue, Node, JavaScript, jQuery, CodeIgniter, and Bootstrap – been hooked on them forever! I'm all about putting in the work and staying committed. Ready to join me on this journey to coding?"