Calculation of time intervals based on input values from text boxes, calculating quarters of an hour

I am facing a couple of challenges:

-I am trying to calculate the time duration in hours between two military times input by the user in two textboxes. The result should be in quarter-hour intervals like 2.25 hours, 2.75 hours, etc.

-The current calculation I have is showing a formatting error upon submission.

I have a form where I need to compute the difference in hours between a start-time and an end-time, entered in military (24-hour) format. Since employees are paid in quarter-hour increments, the output should display the total hours down to the quarter-hour (e.g., 4.25 hrs, 4.75 hrs, etc).

Due to the structure of the form, the start-date/time and end-date/time are in separate textboxes. Additionally, some browsers do not support input type="time", so I had to use textboxes with type="number" instead.

Here is the ASP code snippet:

<label for="tbBeginningTime">beginning time</label>
<asp:TextBox runat="server" ID="tbBeginningTime" type="number" AllowNegatives="false" onblur="javascript:hoursCalc();"></asp:TextBox>

<label for="tbEndingTime">ending time</label>
<asp:TextBox runat="server" ID="tbEndingTime" type="number" AllowNegatives="false" onblur="javascript:hoursCalc();"></asp:TextBox>

<label for="tbTotalTime">total time</label>
<asp:TextBox runat="server" ID="tbTotalTime" type="number" ReadOnly="true" AllowNegatives="false"></asp:TextBox>

I have used JavaScript to perform a basic calculation to determine the hours, but I am struggling to handle the quarter-hour decimal points (.25, .50, .75). I attempted to use modulus to separate out the decimals and also tried splitting them into an array, but the correct result did not appear in the tbTotalTime textbox.

Here is the relevant JavaScript code:

function hoursCalc () {
        var startTime = document.getElementById('<%= tbBeginningTime.ClientID %>');
        var endTime = document.getElementById('<%= tbEndingTime.ClientID %>');
        var totalTime = document.getElementById('<%= tbTotalTime.ClientID %>');
        var t1 = 0;
        var t2 = 0;

        if (startTime.value != "") t1 = startTime.value;
        if (endTime.value != "") t2 = endTime.value;

        if (endTime.value < startTime.value) t2 = parseInt(endTime.value) + 2400;

        totalTime.value = parseInt((parseInt(t2) - parseInt(t1)) / 100);
    }

While this calculates the hours and displays it in the tbTotalTime textbox, I encounter an error when trying to submit the form with a parameterized SQL insert statement, stating "Input string was not in a correct format."

Below is the C# code I am using:

protected void btnSaveClick(object sender, EventArgs e)
    {
        string connstring = ConfigurationManager.ConnectionStrings["TimeHubDBCS"].ConnectionString;
        using (SqlConnection conn = new SqlConnection(connstring))
        {
            try
            {
                SqlCommand cmd = new SqlCommand("spInsertRequestCO", conn);
                cmd.CommandType = System.Data.CommandType.StoredProcedure;

                cmd.Parameters.Add("@BeginningTime", SqlDbType.Time).Value = DateTime.ParseExact(tbBeginningTime.Text, "HHmm", null).TimeOfDay;
                cmd.Parameters.Add("@EndingTime", SqlDbType.Time).Value = DateTime.ParseExact(tbEndingTime.Text, "HHmm", null).TimeOfDay;
                cmd.Parameters.Add("@TotalTime", SqlDbType.Int).Value = int.Parse(tbTotalTime.Text);

                conn.Open();
                cmd.ExecuteNonQuery();
                conn.Close();

                SuccessMessage = "Request Saved Successfully";
                DisplaySuccessDialog(null, null);

                ConfigureButtons(null, null);
            }
            catch (Exception ex)
            {
                PopupTitle = "Save Error: ";
                ErrorMessage = ex.Message;
                DisplayErrorDialog(null, null);
            }
        }
    }

I understand that this might be a complex question, and I might receive some downvotes for it. However, I am seeking any suggestions or guidance to streamline this process.

Answer №1

An error message appears indicating "Input string was not in a valid format."

This error occurs when you attempt to pass a value to a method that differs from what the method expects.

If you insert breakpoints in your button click code, you will notice that the error arises from this line.

cmd.Parameters.Add("@TotalTime", SqlDbType.Int).Value = int.Parse(tbTotalTime.Text);

The issue lies specifically in the int.Parse(tbTotalTime.Text) section. The int.Parse function requires a string that can be converted to an integer value (e.g. "3"). However, when your code is executed, it encounters an empty string causing int.Parse to fail in converting it to a valid numeric value.

Despite your javascript setting the value for the field, it is not accessible in your server-side code due to the view state. Disabling the view state for this field should resolve the issue.

<asp:TextBox runat="server" ID="tbTotalTime" type="number" EnableViewState="false"
                                                    AllowNegatives="false"></asp:TextBox>

Furthermore, whenever you encounter errors, try incorporating breakpoints in your code for debugging purposes. This approach will facilitate identifying the specific section of code that is causing the issue. It enables you to inspect variable values and more during the debugging process.

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

Slider malfunctioning following AJAX loading

After the user clicks on #mail-wrap, I am attempting to trigger the ready event which loads another page with AJAX so that sss() can be refired. Despite my efforts, it seems like it is not working as expected. Can you help me identify what might be going w ...

Numerous buttons activating a single modal component

I have an array called videos, which contains objects of the type Video (defined below). My goal is to create a functionality where clicking on a specific video button opens a modal containing information about that particular video. interface VideosInfo ...

What is the process for removing a Discord user using Node.js?

I've been working on creating a discord bot using node.js, but I'm facing an issue where nothing happens when I try to use a command. The console doesn't log anything except for the bot coming online. const Prefix = '$'; bot.on(&a ...

Interactive font-awesome icons within an interactive dropdown menu

I am currently facing an issue with using two Fontawesome icons in a clickable dropdown menu. The dropdown menu does not toggle when I click on the icons directly; however, it works when I click on the padding around them. The example provided by W3schools ...

Storing a birthday in a database using ASP.NET and saving it as a date type

Hello, I am trying to save birthday information using a date picker in ASP.NET. In my database, the data type is Date. However, I have attempted to save the data but it's not working properly. Can someone please provide guidance on this issue? produc ...

How can you verify the anticipated log output in the midst of a function execution with Jest unit testing?

Below is a demonstration function I have: export async function myHandler( param1: string, param2: string, req: Request, next: NextFunction, ) { const log = req.log.prefix(`[my=prefix]`); let res; If (param1 === 'param1&a ...

Unable to locate the 'react-native' command, attempted various fixes but none were successful

Working on an older react native project that was functioning perfectly until I tried to pick it back up and encountered a problem. https://i.stack.imgur.com/1JUdh.png This issue revolves around the package.json file. https://i.stack.imgur.com/v6ZEf.png ...

Choose all the checkboxes that use Knockout JS

Struggling with implementing a "select all" checkbox feature as a Junior developer on a complex project utilizing knockout.Js and Typescript. I can't seem to figure out how to select all existing checkboxes. Here is the HTML: <td> <inp ...

Inquiry about Date and Time Selection Tool

I am working on a PHP project that includes two textboxes: one for selecting dates and the other for choosing a specific time. What I need assistance with is disabling any times before the selected date in the second timepicker textbox if today's dat ...

Improving Performance in JQuery to Prevent Page Flickering

After experimenting with different code variations in the Masterpage to prevent page flickering when navigating, I found that while removing certain lines reduced flickering, it also resulted in double page reloads or blank pages. What would be the most ...

The configuration of the Braintree API client is incorrect: the clientApiUrl found in the clientToken is not valid

Error Found: Braintree API Client Misconfiguration - The clientApiUrl provided in the clientToken is invalid. Upon checking my browser log, I noticed this error. I am using a Node backend with an Angular front end and integrating Braintree javascript SDK ...

Steps to seamlessly integrate puppeteer with an active Chrome instance or tab

Is there a way to connect puppeteer to an already open Chrome browser and control a specific tab? I believe it may involve starting Chrome with the --no-sandbox flag, but I am unsure of the next steps. Any assistance on this matter would be greatly apprec ...

Having trouble locating a button on Trello using Selenium in C#

I have been working on automating the Trello Activity extension, specifically trying to use Selenium to automatically click the "Export to CSV" button. In my code, I am attempting to locate the button using xPath: driver.FindElement(By.XPath("//[@id=&bsol ...

Iterate over Observable data, add to an array, and showcase all outcomes from the array in typescript

Is there a way to iterate through the data I've subscribed to as an Observable, store it in an array, and then display the entire dataset from the array rather than just page by page? Currently, my code only shows data from each individual "page" but ...

Tips for keeping a login session active on multiple tabs

As I am in the process of developing a website, one issue I am facing is determining the most effective method to maintain user login sessions. Currently, I am utilizing Html5 web storage known as "session storage" to keep track of whether a user is logged ...

How to flip the value in v-model using VueJS

Below is the code snippet that I am working with: <input v-model="comb.inactive" type="checkbox" @click="setInactive(comb.id_base_product_combination)" > I am looking to apply the opposite value of comb.inactive to the v-model. Here are m ...

Encountering null values in IE8/IE7 JavaScript code

Although I am not a JavaScript expert, I have a simple function that works perfectly in all browsers except for IE8 and 7. function setSelected() { var backgroundPos = $('div.eventJumpToContainer').find('.selected').css('backg ...

Can you define the "tab location" in an HTML document using React?

Consider this component I have: https://i.stack.imgur.com/rAeHZ.png React.createClass({ getInitialState: function() { return {pg: 0}; }, nextPage: function(){ this.setState({ pg: this.state.pg+1} ) }, rend ...

Is it possible to use a component created in the newest version of Angular in apps developed with older versions of Angular?

I am interested in developing a component using the most recent version of Angular. However, my intention is to use this component in two distinct Angular applications - one created with Angular 6 and another with Angular 10. Is it feasible to achieve this ...

The error occurred while trying to cast the value of "{{Campground.name}}" to an ObjectID. This value, which is of type string, could not be converted to an ObjectID at the path "_id" for

const express = require("express"); const session = require("express-session"); const cookieParser = require('cookie-parser') const mongoose = require("mongoose"); const { Campground, User, Review } = require(" ...