jQuery Difference Between Two Dates in Hours Minutes and Seconds

Share this Article
Reading Time: 3 minutes
486 Views

Inside this article we will see the concept i.e jQuery Difference Between Two Dates in Hours Minutes and Seconds. Article contains classified information about calculating time difference in hours, minutes and seconds.

In this article we will use a jquery plugin i.e moment js. This plugin used in jquery to work with date time functions. We will use it to find the difference between two dates into Hours, Minutes.

Learn More –

Let’s get started.

Application Programming

Create a file called it as index.html inside any project folder. Open index.html and write this code into it.

<!DOCTYPE html>
<html>

<head>
    <title>Moment Difference Between Two Dates in Hours Minutes and Seconds</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" crossorigin="anonymous"></script>
</head>

<body>
    <div style="text-align: center;">

        <h2>Moment Difference Between Two Dates in Hours Minutes and Seconds</h2>

        <h3 id="datetime"></h3>
    </div>

    <script type="text/javascript">
        $(function() {

            var startTime = moment('02-01-2021 01:01:01', 'DD-MM-YYYY hh:mm:ss');
            var endTime = moment('03-01-2021 16:52:53', 'DD-MM-YYYY hh:mm:ss');

            var hoursDiff = endTime.diff(startTime, 'hours');
            var minutesDiff = endTime.diff(startTime, 'minutes');
            var secondsDiff = endTime.diff(startTime, 'seconds');

            datetime = 'Hours:' + hoursDiff + ', Minutes:' + minutesDiff + ', Seconds:' + secondsDiff;

            $("#datetime").html(datetime);
        });
    </script>
</body>

</html>

Concept

var startTime = moment('02-01-2021 01:01:01', 'DD-MM-YYYY hh:mm:ss');
var endTime = moment('03-01-2021 16:52:53', 'DD-MM-YYYY hh:mm:ss');

var hoursDiff = endTime.diff(startTime, 'hours');
var minutesDiff = endTime.diff(startTime, 'minutes');
var secondsDiff = endTime.diff(startTime, 'seconds');

Application Testing

Now,

Open into browser.

URL: http://localhost/moment-js/index.html

We hope this article helped you to learn jQuery Difference Between Two Dates in Hours Minutes and Seconds Tutorial in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Was this post helpful?

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5