Guidelines for verifying that a specified time falls within a designated range using Javascript

Need assistance with validating the start time and end time input values to ensure they fall within a specified range. Everything works fine when both times are on the same day, but encounters issues when the end date is different. I've searched through numerous StackOverflow posts without finding a solution.

How to check if one DateTime is later than another in JavaScript

Comparing two time strings in HH:MM:SS format

Check if one DateTime is later than another in JavaScript https://i.sstatic.net/RKET8.png

<html>
<script language="javascript">
    jQuery(document).on('change',".timepicker",function(){
var selectedTime = new Date("November 13, 2018 " + jQuery(this).val());
var startLimit = new Date("November 13, 2018 " + jQuery(this).data('starttime'));
var endLimit = new Date("November 13, 2018 " + jQuery(this).data('endtime'));
var start_time_val = new Date("November 13, 2018 " + $("input[name=start_time]").val());
var end_time_val = new Date("November 13, 2018 " + $("input[name=end_time]").val());
var elementName = jQuery(this).attr('name');
var valid = moment(jQuery(this).val(), "H:mm a", true).isValid();
var time = new Date("November 13, 2018 " + selectedTime);
jQuery(this).next('span.error').text('');
var error_msg = jQuery(this).data('erro_msg');


if(valid){
    if(elementName == 'start_time'){

        if(selectedTime >= startLimit && endLimit > selectedTime){

            console.log("selected Time less than start limit");
        }else{
            console.log("selected Time is less than start limit");
            jQuery(this).next('span.error').text(error_msg);
        }
    var endTimeSelected = jQuery(this).next('input').val();
    }else if(elementName == 'end_time'){


        if(selectedTime >= startLimit && endLimit > selectedTime){
        }else{
            jQuery(this).next('span.error').text(error_msg);
        }
        var endTimeSelected = jQuery(this).next('input').val();
    }else if(elementName == 'end_time'){
        if(selectedTime <= endLimit && selectedTime <= endLimit){

        }
        else{

            jQuery(this).next('span.error').text(error_msg);
        }

        var startTimeSelected = jQuery(this).prev('input.timepicker').val();
}
}else{
    jQuery(this).next('span.error').text(error_msg);
}

});
        </script>

<input type="text" name="start_time" value="6:15 AM" class="form-control timepicker" autocomplete="off" requried="1" data-starttime="6:00 AM" data-endtime="12:00 PM" data-erro_msg="Please select time between 6:00 AM-12:00 PM">

    <input type="text" name="end_time" value="7:15 AM" class="form-control timepicker" autocomplete="off" requried="1" data-starttime="6:00 AM" data-endtime="12:00 PM" data-erro_msg="Please select time between 6:00 AM-12:00 PM">
       </html>

Answer №1

The problem lies in the parsing function. Using Date.parse() does not account for the am/pm format. One possible solution is to utilize moment.js or manually separate the am/pm indicator and adjust by 12 hours if it is pm.

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

What steps can I take to update this HTML document and implement the DOM 2 Event Model?

I'm struggling with converting my document from the DOM 0 Event model to the DOM 2 Event model standards. I've tried getting help from different tutors on Chegg, but no one seems to have a solution for me. Hoping someone here can assist me!:) P. ...

The function angular.isNumeric does not exist in this context

Recently, I added the following code to an AngularJS controller to test number values: $scope.isNumeric = angular.isNumeric; However, I encountered the following error: TypeError: angular.isNumeric is not a function I wanted to check if a value is a ...

Create a responsive iframe that expands to fullscreen when a button is clicked

Currently, I am using the following code to create an adaptive iframe with a fixed ratio for both width and height: <div id="game-container" style="overflow: hidden; position: relative; padding-top: 60%"> <iframe style="position: absolute; width ...

Navigating through the additional plugins in WebDriver

After installing a plugin in Chrome, the next step is to access it through webdriver. Here's how you can do it: File addonpath = new File("path of .crx file"); ChromeOptions chrome = new ChromeOptions(); chrome.addExtensions(addonpath); WebDriver dri ...

Encountering difficulties while attempting to deploy NodeJS application on Heroku

When attempting to deploy my nodejs app, I encountered the following error: 2019-11-25T18:16:16.927748+00:00 app[web.1]: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c9a8a7a6a7b0a4a6bcbae4afa6bbbca4e4ada0baaabcbabaa0a6a ...

Ways to merge values across multiple arrays

There is a method to retrieve all unique properties from an array, demonstrated by the following code: var people = [{ "name": "John", "age": 30 }, { "name": "Anna", "job": true }, { "name": "Peter", "age": 35 }]; var result = []; people. ...

Transmit parameters via onclick event on FullCalendar

I have been utilizing the full calendar feature and it's been functioning properly. However, I am encountering an issue with sending parameters via onclick event. Below is the JavaScript code that I currently have: <script> $(document).ready(fu ...

What is the best way to declare strings within a Typescript interface?

I have an array of Projects with multiple strings in the stack property const projects: IProject[] = [ {name: '', description: '', stack: {'php', 'sql'}} ] What is the best approach for defining the interface? ...

How to access elements in every document fragment

I am facing an issue with a page that contains multiple document fragments. I need to retrieve all elements from the entire page that match a specific selector, like so. document.querySelectorAll('iframe') However, this does not return elements ...

Can JavaScript be utilized to retrieve the MAC address?

Is it possible to retrieve the Mac addresses of a system for login using JavaScript? ...

Challenges with differentiating between addition and concatenation in Vue computed properties

Recently diving into Vue and came across an intriguing issue, I am curious to know the reason behind it and how to prevent it. <template> <div> <input type="number" v-model="a" style="color: white" /> <input type="number" v- ...

Node timers exhibiting unexpected behavior contrary to documented specifications

Feeling a bit lost with this one. I'm running Ubuntu and using nvm for node. I made sure to uninstall the version of node installed via apt just to be safe. node --version > v10.10.0 npm --version > 6.4.1 So, I go ahead and create-react-app a ...

Is there a PHP script available to verify the status of FTP servers and determine if

I am in need of creating a PHP script that is triggered by a setInterval("ajaxrequest('ftp.php', 'context')", 1000) function. The PHP script itself is quite simple. It consists of an array containing FTP addresses. The script loops thro ...

The ng-change functionality of Angular radio buttons only functions correctly the first time it

I am struggling to comprehend why the angular ng-change function is only being called on the first click. Take a look at this example: http://jsfiddle.net/ZPcSe/5/ The function in the provided example is triggered every time the radio selection is change ...

Enabling Multi-Row Form Submission in jQuery: Ensure Submit Button is Disabled Until Every Row Has a Checked

I am dealing with a multi-row form that contains single choice radio buttons in each row. My goal is to have the final <button> tag disabled until a radio button has been checked in each row. Although I have found a solution from a previous question ...

Pass the retrieved object back to the calling function in NodeJS using asynchronous MySQL operations

I'm diving into NodeJS for the first time and struggling to create a reusable function that can execute a query passed as a parameter and then return the response to the caller. This approach is necessary as there are over 100 functions in need of dat ...

What is the method for ending the mouseleave effect?

Clicking on the box will trigger a change in the text on mouseleave. Clicking on the button will also cause another change in the text. How can we revert the text back to its original position after removing the effects triggered by clicking the button and ...

Is there a performance boost when using queue() and filter() together in jQuery?

I'm currently refactoring some Jquery code and I've heard that chaining can improve performance. Question: Does this also apply to chains involving queue() and filter()? For instance, here is the un-chained version: var self = this, co = ...

Adding a panel dynamically with Bootstrap incorrectly

I have been using the Collapse panel in Bootstrap and it was working perfectly when implemented statically. However, I encountered an issue when trying to add it dynamically. HTML <form> <div class="form-group" > <label for="c ...

Navigating through web applications can be made easier by combining Vue Router

In my applications, I have a variety of routes: GET /game/{any} For this route, Laravel auth middleware provides protection. Within this Laravel route, I plan to create a Single Page Application (SPA) and implement Vue router: const routes = [ { path: ...