Finding differences between two 24-hour format times using moment.js

Is there a way to compare two times in 24-hour format using the code below?

     $("#dd_start_timing, #dd_end_timing").on('keyup change keydown', function() {
        var DutyDayStartTime = $("#dd_start_timing").val().trim();// 13:05
        var DutyDayEndTime = $("#dd_end_timing").val().trim(); // 13:05
        if(DutyDayStartTime.minute() === DutyDayEndTime.minute())
        {
          alert("cannot be same");
        }
});

I am currently utilizing moment.js library for this task. However, an error message "DutyDayStartTime.minute is not a function" keeps appearing. I would appreciate it if someone could guide me on how to compare two times using moment.js.

Answer №1

If you wish to compare two time variables, you can simply utilize the following functions:

  • isSame()
  • isSameOrBefore()
  • isSameOrAfter()
  • isAfter()
  • isBefore()

The aforementioned functions are part of moment.js and return boolean values (True or False). Further details can be found in the official documentation.

var exampleStartTime = moment($("#dd_start_timing").val().trim(), 'HH:mm'); // 13:05
var exampleEndTime = moment($("#dd_end_timing").val().trim(), 'HH:mm'); // 13:05

if(exampleStartTime.isSame(exampleEndTime))
{
  alert("The start and end times cannot be the same.");
}
else if(exampleStartTime.isBefore(exampleEndTime))
{
  alert("The start time must occur after the end time.");
}

Answer №2

To achieve the desired result, utilizing the moment js library is crucial.

const moment = require("moment");

const startOfDay = moment([8, 30], "HH:mm");
const endOfDay = moment([17, 0], "HH:mm");

const durationInMinutes = endOfDay.diff(startOfDay, 'minutes');

Answer №3

start = moment('01:01', 'HH:mm')

end = moment('02:01', 'HH:mm')

duration = end.diff(start, 'minutes')

Answer №4

Comparing the timestamps

var StartTime = moment('08:00', 'HH:mm');
var EndTime = moment('17:30', 'HH:mm');
if(StartTime.unix() === EndTime.unix()){
 console.log('Start time and end time cannot be the same')
}

JSFiddle Unique Solution

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

The return value from vue-query is ObjectRefImpl, not the actual data

Greetings to the Vue.js community! As a newcomer to Vue.js, I am seeking guidance on fetching data using vue-query, Vue.js 3, and the composition API. The data returned to me is ObjectRefImpl, but when I try to print the values, I encounter the error: "Pro ...

Using JQuery Ajax to post an array

I have searched extensively for solutions, but none seem to fit my situation. Currently, I am utilizing the Jquery-Plugin DataTable with multiple tables within a form. The exact number of tables is unknown. The challenge lies in retrieving form data from ...

What is the best way to align a modal with a layout when it appears far down the components hierarchy?

Struggling with creating a React modal and facing some issues. Let's consider the structure below: React structure <ComponentUsingModal> <Left> <ButtonToActivateModal> ... </ButtonToActivateModa ...

Incorporated asynchronous functionality, struggling to integrate it into the code

Previously, I used to utilize the following code for handling state: //get state MyClass.prototype.getState = function(key) { var value; switch(this._options.type){ case "cookie": value = $.cookie(key); ...

Encountering an error when attempting to iterate over an undefined property using an API

I am trying to fetch all classes and their assignments from Google Classroom. I successfully used Google's example code for listing the classes, but had to write my own code for listing the assignments. While the code runs as expected and lists the as ...

Hovers and click effects for navigating through images

The website I'm currently working on is stipz.50webs.com. p.s. HOME functionality is not active at the moment. Having successfully implemented the onhover and onmouseout features, my next goal is to enhance the navigation effects for each div/img so ...

The issue arises with loading data from the server due to lack of definition of Mongo

I am experiencing a console bug and need assistance. It seems that there is an issue with loading data from the server as I am getting an error stating "Mongo is not defined." C:\Users\Robert\Desktop\FINISH\node_modules\mongod ...

Controlling the Escape Key and Clicking Outside the Material-ui Dialog Box

I am currently utilizing material-ui's dialog feature. In this setup, when a user clicks the "sign out" button, a dialog box opens with options to either confirm the sign out by selecting "yes" or cancel it by choosing "no". The issue arises when the ...

The issue of not displaying results in a DIV when using CakePHP 2 and jQuery

I'm having trouble creating an auto-refreshing DIV with updated data. Despite everything appearing to be correct, it's not displaying any results on the webpage. Any assistance would be greatly appreciated :) Controller: public function homeNe ...

The login process in Next-auth is currently halted on the /api/auth/providers endpoint when attempting to log in with the

My Next-auth logIn() function appears to be stuck endlessly on /api/auth/providers, as shown in this image. It seems that the async authorize(credentials) part is not being executed at all, as none of the console.log statements are working. /pages/api/au ...

Switching between Login Form and Register Form in VueJS template

Recently, I attempted to switch between the 'Login Form' and 'Register Form' using code that I found on codepen Flat HTML5/CSS3 Login Form. While the code functioned properly on its own, when integrated into a Vue Template, the form fai ...

Generating a fresh object from an existing object by incorporating updated values using Angular and Ionic version 3

Currently, I am actively working on an Ionic 3 project that utilizes Angular framework. Within my project, I have a JSON object called 'person' which consists of data fields such as name, job, and home. One feature in my app is an Ionic toggle b ...

Tips for fixing a type error in javascript/cypress

While learning cypress and javascript, I encountered this type error: TypeError: _testElements.default.selectionRow is not a function I have thoroughly reviewed the documentation for cypress but cannot seem to find any errors in my code. I'm hoping ...

Sending an Ajax POST request from a Node.js server

I am running a Node.js server with Socket.IO that communicates with a Python server using Django. I am looking to make a POST request from the Node.js server to the Django server on a specific method without utilizing any jQuery functions due to their depe ...

I've been waiting forever for Product.find() to return some results, but it seems to

I have been encountering an issue where my code is supposed to return an empty object of a product but instead it just keeps loading forever. I have thoroughly checked through the code and explored every possible scenario where an error could be occurring, ...

Encountering a null sessionId exception with Selenium RC while attempting to activate the JQuery AddLocationStrategy feature

I've been struggling all day to activate JQuery locators in Selenium RC by trying various suggestions found online, but unfortunately, without any success. I followed the recommendations from this thread on enabling JQuery locators: How do I add a JQ ...

I am encountering an issue with the useRef function not properly detecting visibility

I'm looking to incorporate a fade-in animation into my React div as I scroll and reach a specific section. Unfortunately, the useEffect function that is supposed to detect the scrolling behavior seems to be malfunctioning and I can't figure out w ...

Angular backslash is encoded

Experiencing the same issue as this individual: angularjs-slash-after-hashbang-gets-encoded The URL is getting encoded and not routing correctly, causing it to fall to the otherwise in my route config. I have not been able to identify the root cause yet, ...

A helpful guide on extracting JSON data using AJAX POST method within Django views

I am currently working on parsing JSON data within a Django view, however I have encountered an issue. Below is the code snippet that I am using: $(document).ready(function(){ $("#mySelect").change(function(){ selected = $("#mySelect option:s ...

CoffeeScript's alert feature appears to be malfunctioning

After stumbling upon CoffeeScript in a blog post, I was excited to try it out. My first attempt at using it involved this code snippet: alert "Hello CoffeeScript!" Unfortunately, it didn't work as expected and produced the following error message: ...