Checking if the current time is within 45 minutes of a specified time and if the present time is later than the specified time using an

I'm currently learning how to work with 'angularJS' and struggling with creating a function that can determine if a given 'time' is within 45 minutes of now, and also if the 'time' has already passed (meaning, if now is after the specified time).

function checkTime(time) {
    var currentDate = new Date();
    var chosenDate = new Date((currentDate.getMonth() + 1) + "/" + currentDate.getDate() + "/" + currentDate.getFullYear() + " " + time);
    var diffMinutes = (chosenDate.getTime() - currentDate.getTime()) / (60 * 1000);
    return (diffMinutes > 40 || (diffMinutes < 0 && diffMinutes > -1395));
}

This code snippet is what I've come up with so far. It checks whether the specified time is less than 45 minutes from now.

Any advice or guidance on improving this would be greatly appreciated!

Answer №1

Using momentjs for the solution.

Angular-specific directive for moment.

Read more about Moment js here.

To start, install moment via bower:

bower install angular-moment moment --save

Make sure to include moment in your application:

<script src="components/moment/moment.js"></script>
<script src="components/angular-moment/angular-moment.js"></script>

( If using grunt, running grunt serve will automatically include these scripts after utilizing --save during bower install )

Add the angularMoment module to your app.

var myapp = angular.module('myapp', ['angularMoment']);

You can now utilize momentjs in your controllers. It's recommended to use moment due to its simplicity when working with dates compared to pure javascript.

The issue at hand is determining if a specific time is before or after now within a specified timeframe (45 mins). Imagine a circle with a radius of 45 mins and now located at the center. Everything inside this circle signifies correctness while everything outside indicates incorrectness. https://i.sstatic.net/JM5dn.png

In addition, it's important to identify whether something lies in the past, denoted by being on the left side of the circle.

For reference, let's consider the center as algebraic 0.

n represents the circle radius (45 mins).

If t is the argument (time provided), then to ascertain its position:

f(t) = n - t
If f(t) falls between 0 and t, it is on the right side. 
If f(t) falls between t and 2t, it is on the left side (signifying the past). 

Now, let's implement this logic using momentjs:

function checkTime(time){
    var now = moment(new Date());
    var later = now.add(45*60,'seconds');
    var givenTime = moment(new Date(time));
    var ft = later.millisecond() - time.millisecond();
    if ( ( ft > 0 ) && ( ft < 2700000 ) )//45*60*1000
        return false; // future
    if ( ( ft > 2700000 ) && ( ft < 2*2700000 ) )
        return false; // past
    return true;
}

Answer №2

Give this a shot.

const currentDate = new Date();
const customDate = new Date((currentDate.getMonth() + 1) + "/" + currentDate.getDate() + "/" + currentDate.getFullYear()+ " " + time);

const timeDifference = currentDate.getTime() - customDate.getTime();
const minutesDifference = timeDifference.getMinutes();
return (minutesDifference > 40 || (minutesDifference < 0 && minutesDifference > -1395));

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

Utilize the Webpack library and libraryTarget settings to establish our own custom library as a global variable

I currently have a library named "xyz" that is being imported as a node module from the npm registry. Now, I want to incorporate it as a library and make it accessible under the global name "abc". To achieve this, I plan to utilize webpack configuration. ...

What could be hindering my jQuery function from running the Ajax script?

My jQuery function is supposed to retrieve two values, one for school/college and one for state, and send it to the controller class under the URL "Type&State". However, for some reason, the data is not being passed and nothing is shown in the console ...

Is checking for an email address in a form necessary?

I am currently in the process of creating a coming soon page. I have included a form on the page where users can sign up using their email addresses, which are then sent to me via email. However, I need assistance in determining how to verify that the in ...

Python script for extracting content from web pages that are loaded dynamically

I am facing an issue with extracting content from a webpage on my website. Despite trying to use selenium and clicking buttons, I have not been successful. #!/usr/bin/env python from contextlib import closing from selenium.webdriver import Firefox import ...

One-off object property bindings in Angular

Looking to optimize the performance of my app, I encountered a specific issue. Consider having an object with multiple unchangeable keys within it and a view structured as follows: <div ng-if="vm.model"> <span>{{ vm.model.property1 }}</ ...

When using `JSON.stringify`, the resulting data may vary from the original object

Here is the code snippet in question: console.log("444444: ", profile, JSON.stringify(profile)) Upon checking the log output: https://i.stack.imgur.com/LzalV.png I am trying to understand why I cannot see the value: [0] present Additionally, ...

Unit Testing AngularJS Configuration in TypeScript with Jasmine

I'm in the process of Unit Testing the configuration of a newly developed AngularJS component. Our application uses ui-router for handling routing. While we had no issues testing components written in plain Javascript, we are encountering difficulties ...

Maintain HTML formatting when page is refreshed

I am new to HTML and JavaScript, and I'm trying to modify the JavaScript code below so that when I reload the page, it retains the most recent active tab instead of defaulting back to the first tab. Currently, if I click on the second tab for "Paris" ...

Is it possible to adjust the height of the apprequests dialog?

I attempted the following code snippet: FB.UIServer.Methods["apprequests"].size = {width:600,height:320}; The width successfully adjusts, however, the height is restricted to a fixed value. Appreciate any help! ...

Converting an HTML ul-li structure into a JavaScript object: Steps to save the structure

My HTML structure uses ul and li elements as shown below: <ul class="treeview" id="productTree"> <li class="collapsable lastCollapsable"> <div class="hitarea collapsable-hitarea lastCollapsable-hitarea"></div> <span ...

Avoiding redundancy by establishing the loading state in a redux reducer

Let's dive into a concrete example to better illustrate my point. In the webapp I'm working on, users can apply for jobs using a job reducer that handles various actions such as creating_job, created_job, fetching_job, fetched_job, fecthing_jobs, ...

How can one create a function that delays the execution of code until AJAX data is received

I developed a CKEditor plugin that fetches data via ajax to create RichCombo functionality. The plugin functions correctly, however, when there are multiple instances of the editor on a single page, each plugin ends up sending its own ajax request, leading ...

Reverse a filter within an ng-repeat loop - AngularJS

I have a question that I haven't found the answer to yet. Here is the issue I'm facing: The JSON data I am working with has this structure: [{ "batch_queue_name": "Batch One", "start_date": "12/01/2016 10:18 P.M.", "end_date": "12/03/2016 ...

The Expressjs router prioritizes resolving before retrieving data from Firestore

UPDATE: Upon further investigation, I discovered that by adding "async" to the function signature, the output now displays in the intended order. However, I am still encountering an error regarding setting headers after they have already been sent, even th ...

After the element has been inserted, dom.byId will give you an undefined response

I have encountered an issue with a function that adds a div as a child to a dijit/layout/contentpane. The problem arises when I attempt to reference this div using dom.byId after adding it to the content pane. The function is triggered by a click event on ...

Optimizing resources by efficiently adding an event listener on socket.io

Recently, I've been delving into how JavaScript manages functions. Let's consider an example: io.on("connection", function(socket) { socket.on("hi", function(data) { socket.emit("emit", "hey") }) }) ...

Unable to access a user's public information using Instagram's API

I've spent the past week trying to create a simple Instagram preview application that should show a user's public data such as username, followers, following, and profile picture URL, but unfortunately, I haven't been able to find a solution ...

How to dynamically insert li elements into a ul list using the .after() method

After trying to add an li element to the ul list, I noticed that my DOM wasn't updating when checking the page source. Even attempting to delete elements with the delete button didn't seem to work as expected. Here is the code snippet below. ...

`"Attempting to access keys of a non-object value" - Dealing with JSON and React Native`

Having trouble with React Native and JSON structure? No worries, we've all been there at some point! Don't sweat it if you're still new to React and JavaScript - we're here to help! Let's take a look at the JSON structure causing ...

Trigger a click event in jQuery to activate a form through a hyperlink

I'm facing an issue where I want to implement a password-reset form based on a certain flag being triggered. Currently, my code is set up to prompt the user to change their password if the password_changed_flag is not present. Depending on the user&ap ...