Discrepancy in time is causing an error with the date

I am facing a situation where I need to display the total time worked by an employee after calculating the InTime and OutTime from the first two input fields.

Here's how it works:

The first input field is for the user to enter the INTIME

The second input field is for the user to enter the OUTTIME.

Once both values are added, the third input field will show the total hours the employee has been working.

This is what I have attempted so far:

HTML

<tr>
            <td>
                <asp:Label ID="lblInTime" runat="server" Text="In Time" Visible="true"></asp:Label>&nbsp;
                <asp:TextBox ID="txtInTime" runat="server" Width="89px"></asp:TextBox> (HH:MM)
                <asp:RegularExpressionValidator ID="regIntime" runat="server" ControlToValidate="txtInTime"
                    ErrorMessage="Please enter time in correct format" ValidationExpression="^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$"></asp:RegularExpressionValidator>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="lblOutTime" runat="server" Text="Out Time" Visible="true"></asp:Label>&nbsp;
                <asp:TextBox ID="txtOutTime" runat="server" onkeyup="sum();" Width="89"> 
                </asp:TextBox> (HH:MM) 
                <asp:RegularExpressionValidator ID="regOuttime" runat="server" ControlToValidate="txtOutTime"
                    ErrorMessage="Please enter time in correct format" ValidationExpression="^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$"></asp:RegularExpressionValidator>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="lblTotalHr" runat="server" Text="Total Hours" Visible="true"></asp:Label>&nbsp;
                <asp:TextBox ID="txtTotalHrs" runat="server" Width="70" ReadOnly="true" onkeyUp="TimeCalculation();">
                </asp:TextBox>
            </td>
        </tr>

JAVASCRIPT

function TimeCalculation() {
       var start = $('#txtInTime').val();
       var end = $('#txtOutTime').val();
       var diff = new Date(end - start);
       $('#txtTotalHrs').val(diff);
   }

However, I encountered an error in the third input field stating:

Invalid Date.

Note: My date format is HH:MM and uses the 24-hour clock

Please advise me on where I might be making a mistake

Answer №1

In order to subtract the start time from the end time, it is necessary to first convert both times into date format.

Modify your JavaScript function as follows:

function CalculateTimeDifference() {
    var startTime = $('#txtStartTime').val();
    var startHours = parseInt(startTime.split(":")[0]);
    var startMinutes = parseInt(startTime.split(":")[1]); 

    var endTime = $('#txtEndTime').val();
    var endHours = parseInt(endTime.split(":")[0]); 
    var endMinutes = parseInt(endTime.split(":")[1]); 

    var differenceHours = endHours - startHours;
    var differenceMinutes = endMinutes - startMinutes;
    differenceHours = ("0" + differenceHours).slice(-2);
    differenceMinutes = ("0" + differenceMinutes).slice(-2); 
    var difference = differenceHours + ":" + differenceMinutes;
    $('#txtTotalTime').val(difference); 

}

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

Using a JavaScript callback function as a parameter for the addJavascriptInterface method in Java

Can Java interact with arbitrary functional objects in JavaScript by calling them as callbacks? For example, if we have a function called 'access' that is registered to invoke a Java function: access(function(blabla){ ... }); Are there eff ...

No data found in response from gRPC Server

Despite my efforts, the JSON object returned from a callback in my gRPC server remains empty. Following a tutorial similar to this one, I have made some modifications such as using a SQLite3 server instead of knex and focusing on the listProducts method. ...

Activate jqGrid's navigation bar save icon when the ondblClickRow event is triggered

After setting the jqGrid row edit on the ondblClickRow event, how can I enable the save icon on the navigation bar when a row is double clicked? ondblClickRow: function (rowid) { jQuery(this).jqGrid('editRow', rowid, true, null, null); ...

An error will be thrown if you try to pass an array attribute of an object as a prop to a React component

I'm trying to grasp why passing an array attribute of a data object into a Component as a prop is causing issues. Is this due to my understanding of how React functions, or are there potential pitfalls in this scenario? Any insight would be greatly ap ...

Using jQuery to Extract Data from an External JSON Source

I am working with a large 2 MB JSON object that I need to parse using jQuery. The entire object has been saved in a file called "timeline.js", and I am looking to extract specific records from it as required. Originally, my dataset was in XML format, but ...

When working with Node.js and Express, I encountered an issue where the req.session object was not defined within

It's peculiar to me that req.session.username is undefined in the tag >>>DOESNT WORK<<< while it works in the tag >>>THIS DOES WORK<<<. I passed req as an argument to my module, but it seems like there might be some ...

Vue - Implementing plugin as a prototype functionality

For notifications in my application, I've incorporated the euvl/vue-notification library. Each time I need to notify the user, I have to include the following code: If I'm within a Vue component: this.$notify({ group: 'panel', ...

Gradually make text disappear while scrolling

On my webpage, I have a background image that remains fixed and centered. When the content on the page is long enough to overflow, I want the text to appear inside the image and fade out as you scroll towards the top or bottom of the image. I do not want a ...

Trigger the execution of the second function upon the successful completion of the first

In the following code, my concept is to display: The clicked kingdom (clicked_id) initiates an attack on (clicked_id). https://i.stack.imgur.com/Bx8QW.png https://i.stack.imgur.com/Cg2GL.png https://i.stack.imgur.com/gUNxM.png How can I trigger the sec ...

Twice the charm, as the function `$("#id").ajaxStart(...)` is triggered twice within an AJAX request

I am trying to implement the following code: <script language="javascript"> function add(idautomobile,marque,model,couleur,type,puissance,GPS){ $("#notification").ajaxStart(function(){ $(this).empty().append("<center><br/><i ...

Whenever a form is generated dynamically, it consistently encounters a 403 forbidden error when attempting to make a POST request

I am encountering an issue with editing text posts on my website. Whenever I click the edit button, a form is dynamically created to replace the div element. I have set up a POST api in Django to handle the submission of this form and edit the existing pos ...

Dynamic search form technology

My HTML view includes a search form and AJAX code to handle the form request $(document).ready(function() { console.log('Ready'); $('.search-wrapper').on('click', '#find-dates', function(a) { a. ...

What is the process for generating an attribute in a system?

If I want to create an element using plain JavaScript, here is how I can do it: var btn = document.createElement('button'); btn.setAttribute('onClick', 'console.log(\'click\')'); document.body.appendChild( ...

Latest versions of Bootstrap are facing issues with the functionality of the Carousel feature

I'm struggling to create a basic carousel, but for some reason, it's not functioning properly. I attempted to use the sample code provided by Bootstrap's documentation, but it doesn't behave as expected (slides won't transition and ...

Ways to loop through a collection of indexed elements

I am working with an array of indexed objects and my goal is to iterate through it in order to transform it into a new flattened array. Here is the initial array of objects: "attentionSchedules": [ { "room": "1", ...

What is the reason behind the function being returned in this situation? (JavaScript)

I'm struggling to understand a piece of code related to handling an onClick event in JavaScript/React. Here is the function: handleButtonClick(key, song) { return () => { document.getElementById(key).play(); this.setState({ ...

immutable chrome sqlite data objects

I have been utilizing a sqlite DB as the storage system for a web application. I have been directly using the objects returned from queries in my application. For instance: function get_book_by_id(id,successCallback,errorCallback) { function _successC ...

Learn how to dynamically populate text fields with data when an option is selected from a dropdown menu that is populated from a database using Laravel and Ajax technologies

Basically, I've included a drop-down menu in my form that retrieves values from the database. The form itself contains input fields, some of which already have values saved in the database. I'm using the drop-down menu to automatically load these ...

Check if any element within a class satisfies the specified condition using Jquery

I am looking to determine if any element within a specific class meets a set of conditions. For example: $(document).on('click','.modalInner_form_nav', function(){ var input = $(this).parents('.modalInner_form').find(' ...

Utilizing requirejs for handling asynchronous callback functions with ajax

If I need to take advantage of the jQuery AJAX API features and customize settings for each ajax call made by my application, it can be done like this: For example, imagine a page that showcases employee information in a table using ajax calls to an API. ...