What is the best method to compare two times and determine if they fall on the same date within an Angular 2/4 application? The time should be in the format of "HH:mm AM

Is there a way to validate if my time period falls on the same date?


let startTime = currentSelection.startTimeHr + ":" + currentSelection.startTimeMin + " " + 
currentSelection.startTimeAMPM;
let endTime = currentSelection.stopTimeHr + ":" + currentSelection.stopTimeMin + " " + 
currentSelection.stopTimeAMPM;

startTime = 02:30 AM
endTime = 06:45 PM

I am looking for a boolean value (true/false) as the validation result.

Answer №1

If you want to compare times, one approach is to convert them into date objects for easy comparison. Here is a simple script that demonstrates this:

var time1 = "02:30 AM",
    time2 = "06:45 PM";

var d1 = new Date(),
    parts1 = time1.match(/(\d+)\:(\d+) (\w+)/),
    hours1 = /am/i.test(parts1[3]) ? parseInt(parts1[1], 10) : parseInt(parts1[1], 10) + 12,
    minutes1 = parseInt(parts1[2], 10);

d1.setHours(hours1);
d1.setMinutes(minutes1);

var d2 = new Date(),
    parts2 = time2.match(/(\d+)\:(\d+) (\w+)/),
    hours2 = /am/i.test(parts2[3]) ? parseInt(parts2[1], 10) : parseInt(parts2[1], 10) + 12,
    minutes2 = parseInt(parts2[2], 10);

d2.setHours(hours2);
d2.setMinutes(minutes2);

if(d1 < d2)
    alert('Time1 is earlier than Time2');
else
    alert('Time2 is earlier than Time1');

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

Encountering a 503 Error in Loading .js Files from Index.html in a .NET 7.0 Angular Application

I recently came into possession of an Angular project that I am trying to set up in IIS, but I am encountering some unusual behavior. Since I am relatively new to Angular, I ask for your patience as I navigate through this issue. Upon loading the website, ...

Determine the character count of the text within an *ngFor loop

I am a beginner in Angular (8) and I am trying to determine the length of the input value that I have created using a *ngFor loop as shown below: <div *ngFor="let panel of panels; index as i" class="panel" [id]="'panel-' + panel.id"> & ...

Is it possible to use uglifyjs to merge multiple files into a single minified file?

I attempted to compress multiple javascript files into one using the uglifyjs tool, but encountered an issue. I ran $node uglifyjs.js to execute the file. Below is the content of the uglify.js file: var fs = require('fs'); var uglifyjs = re ...

An error was encountered: An identifier that was not expected was found within the AJAX call back function

I am experiencing an issue while attempting to query an API. An Uncaught SyntaxError: Unexpected identifier is being thrown on the success part of my JQuery Ajax function. $(document).ready(function(){ $('#submitYear').click(function(){ let year ...

What is the best way to avoid passing a value to a component in nextjs?

I'm trying to make this component static and reusable across different pages without passing a parameter when calling it. Is there a way to achieve this while following the official documentation? component: import { GetStaticProps, InferGetServerSid ...

Utilizing jQuery for manipulating href attributes

Having some trouble with a jQuery selector to click on a link. Any suggestions or solutions? Thanks in advance. $tweet.html(tweet.created_at + ' <a href="#" class="'+tweet.user+'">@' + tweet.user + '</a>: ' + twee ...

Angular - Automatically create thumbnails for uploaded images and videos

I am working on an Angular application that allows users to upload files. My goal is to create thumbnail images for uploaded images and videos without saving them locally. Instead, I plan to pass them along with the original file data to another API. Howev ...

Adding up rows and columns using HTML

I've designed an HTML table to function as a spreadsheet, with the goal of being able to total up rows and display the sum in a cell labeled "Total." The same calculation should be applied to columns as well, with totals displayed in the last column c ...

Updating data in MongoDB using AJAX with Laravel

After successfully using jquery sortable to drag data from one column to another in a view that displays my data, I am now attempting to update an operation in mongo db through ajax. The callback function provides me with the task id and the column headers ...

Learn how to automatically access keys in local storage using Angular

I need to implement a way to store data in local storage so that it persists even when the page is refreshed. In my HTML file, there is a button that triggers a function in my TypeScript file. This function takes a parameter 'game', which is an i ...

Is it a jQuery photo gallery that showcases images sourced directly from a database?

I'm feeling a bit stuck with my coding and could really use some assistance. I am currently working on implementing a jquery gallery plugin that pulls images from a database using a PHP script instead of directly from a folder on the server. <?php ...

Angular 8: Implementing Form Validation with a Boolean Flag

Within my HTML code, I have a function (change)="limitUser($event)". In Typescript, I utilize a for loop to iterate through each element and determine if the value is less than 10. If it exceeds 10, the inValid = true condition is set. All form fields in m ...

Is there a TypeScript alternative to triggering a click event on a specific class using $(".class").click()?

I am currently utilizing a date range picker within an Angular project. <button type="button" class="btn btn-danger daterange-ranges"> <i class="icon-calendar22 position-left"></i> <span></span> <b class="caret"></b ...

Encountering a CORS error after deploying an Angular and Spring Boot application on Heroku

Currently facing challenges with an app due to CORS issues. It functions perfectly locally, but once deployed, an error occurs. Access to XMLHttpRequest at 'https://portafolioback.herokuapp.com/portafolio/version1/post/all' from the origin &apos ...

Factory Pattern Utilizing Enum for Field Population

Struggling to find a solution for setting default values for instances created by the factory method createLetterMap... I don't think the problem lies in 'How to loop over enums' because it seems impossible due to types not being available ...

Storing JSON responses from a web service into a database using Linux wget in the background

I encountered a major issue. I have written a script in jQuery to communicate with a webservice, sending JSON data and receiving JSON responses in return. Here's a snippet of the code: function Product(date_from,date_to,API_KEY) { var self = this; se ...

Routing in Angular app breaks down after selecting a single route

I'm new to Angular and currently working with the Router module. I have a Servers component with 3 servers, and clicking on each server should open the individual server's component on the same page. However, I've encountered an issue where ...

Get the div to occupy the rest of the available height

I am facing a challenge with two divs on my webpage. The bottom one contains content that expands the highest. The page is set to 100% height and width using the CSS property position: absolute. <style> body, html { height:100%, width:100% } ...

No content found in jQuery .text() values within iframe

I am experiencing an unusual issue with assigning a value to a variable using jQuery. I am unable to retrieve the values from .text() specifically on Spotify, while other functions on different sites are working fine. Even after the elements have loaded, i ...

What steps can I take to enhance the quality of my PDF files? Currently, I am utilizing Jspdf in conjunction with html

My current challenge involves generating a PDF file from my application. Although I am able to create a PDF, the quality is not up to par. When I download the PDF, I notice some discrepancies in text quality. While it's not terrible, it's also n ...