How to verify time variance using JavaScript

I have a list of dates in the format "2021-02-25T12:30:00" and I want to filter out those that are at least 24 hours ahead. The code snippet below attempts to achieve this, but seems to have an issue.

const date2 = "2021-02-26T12:30:00";

function getFormattedDate() {
  const currentDate = new Date();
  const formattedDate = `${currentDate.getFullYear()}-${currentDate.getMonth() + 1}-${currentDate.getDate()}T${currentDate.getHours()}:${currentDate.getMinutes()}:${currentDate.getSeconds()}`;
  return formattedDate;
}

if ((Math.abs(new Date(date2.slice(-8)) - new Date(getFormattedDate().slice(-8))) / 36e5) >= 24) {
  console.log("There's enough time");
} else {
  console.log("Not enough time remaining");
}
console.log(date2.slice(-8));

Could someone point out the error in the code?

Answer №1

Here is an example for you to consider

const hours = 1000 * 60 * 60; // 1 hour in ms
const date3 = "2021-03-15T08:00:00";

if (new Date(date3).getTime() - Date.now() >= hours)
    console.log("Plenty of time");
else
    console.log("Time is running out");

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

"Troubleshooting the path problem in Vue.js router version 3.0.1

Encountered an unexpected issue and seeking assistance for resolution. Below is a snippet of the route configuration that I am currently dealing with: routes: [ { path: '/signin', name: 'signin', component: SignIn }, ...

What is the best way to serialize multiple forms with multiple IDs using JavaScript or jQuery?

How can I serialize forms passing multiple id's by reference? Here is what I have: <code> keys = ['someref1','someref2',....,'someref99]; data_serializes = $("#data-"+keys.join(",#data")).serialize(); </cod ...

Create a concise and distinctive identification code from a MongoDB object identifier

Currently, I am developing a patient monitoring system using the MERN stack. One of the requirements is to create a unique patient ID for each patient in a more user-friendly format than the MongoDB object IDs usually used in real-time applications. How ca ...

Size of 2-dimensional array indexed by [i]

Currently coding in C, I have a challenge of implementing a function similar to the length member function found in other languages such as C++. This function is used to determine the size of an array or possibly a vector of data. Is it possible to achie ...

The server will not accept the 'text/html' content type until it is terminated

I am encountering an issue with serving a simple html page through node. When I specify the content type as text/plain, the plain text of the html file loads correctly. However, when I switch it to "content-type" : "text/html", the browser tab keeps loadi ...

How can I extract echoed information from PHP after submitting form data through jQuery Ajax?

I am looking to transfer a file from an input form to a php script using ajax and handle the response echoed by my php script. Here is my HTML form: <form id="fileUploadForm" method="POST" enctype="multipart/form-data"> <input name="fileToU ...

The onEdit() function in Google Apps Script encountered an error indicating that it has exceeded the maximum execution time limit

My script has been running smoothly in Apps Script for the past three weeks, but it suddenly stopped working a few days ago. I noticed that there are multiple executions happening at the same time and many of them are timing out with an error message sayin ...

Nuxt3 - Exclude selected files from type checking

Currently, I am working on a Nuxt3 project and I have encountered an issue where I need to ignore type checking for certain files. UnoCSS is being used and I have created an unocss.config.ts file for its configuration. However, when I try to extend the fon ...

Issue regarding navigation using nuxt-links to pages with hashtags/anchors

When it comes to my website navigation, I rely on nuxt-links a lot. Most of these links direct users to specific sections within the home page using hashes like: <nuxt-link v-else class="text-link" :to="localePath('index') + #hash" > ...

Decode a JSON string that has already been encoded

Currently, I am dealing with JSON strings in which the quotes are not properly escaped. The strings are structured like this: { "foo" : "hello my name is "michael"" } Is there a practical way in JS/PHP to escape the quotes within the value without manual ...

Capturing an aframe scene screenshot and securely uploading it to a server without any annoying popups

The following code snippet: <script src="https://aframe.io/releases/0.8.0/aframe.min.js"></script> <script> AFRAME.registerComponent("foo", { init: function() { document.querySelector('a-scene').components.screensho ...

Tips for efficiently saving and loading every individual character from a 2D array stored within a struct in C programming

I am attempting to store a 2-dimensional array of characters in a file. My 2D array represents a game board where I can make changes such as drawing, resizing, deleting, and adding rows/columns. I am encountering difficulties when it comes to saving the ...

Setting the borderRadius for a web view on Android Maps V3: A complete guide

In my application, I am using Android Map V3 and have encountered a bug specific to the Kit-Kat version. The chromium kit throws up an error message - nativeOnDraw failed; clearing to background color, which prevents the map from being displayed. Despite ...

Casperjs: the secret to moving forward only when an ajax call response is received

I am trying to utilize casperjs for an ajax call that requires waiting for my server's response, which may take up to 3 minutes. However, I have encountered an issue where the casper.then function times out after exactly 30 seconds. I attempted adjust ...

Ensure the content of the file is valid prior to uploading

Is there a method to verify the correctness of a yaml file's syntax and data before uploading it to a server? ...

Pressing the enter key within Material UI Autocomplete will allow you to quickly create new

Wouldn't it be great if Autocomplete in material ui could do this: wertarbyte Imagine being able to insert text (string) without the need for a list of elements to select from. This means that the noOptions message shouldn't appear, and instead ...

Is there a way to dynamically incorporate line numbers into Google Code Prettify?

Having some trouble with formatting code and inserting/removing line numbers dynamically. The line numbers appear on the first page load, but disappear after clicking run. They don't show at all on my website. I want to allow users to click a button a ...

When you click on one item in a jQuery selector array, the action is being applied to all elements within the array

I've been working on implementing a cheat function for a minesweeper game that reveals a random non-bomb square (line 279) and its safe neighboring squares (the 8 squares around it without bombs). However, I'm encountering an issue where using $ ...

Rounding Decimals using JavaScript

I am facing the challenge described in this particular query. In most cases, my code works fine to round numbers to two decimal places with the following formula: Math.round(num * 100) / 100 However, there was a peculiar scenario where it failed. When tr ...

The submenu in Angular Bootstrap 3 navbar fails to trigger

I am currently using Angular 1.2.1 and Bootstrap 3.0.2. When I try to generate a menu using ng-repeat in my plain vanilla nav menu with a drop down, the submenu does not function as expected. Here is the HTML code: <ul class="nav navbar-n ...