Issue with date comparison operator logic

Here's a simple JavaScript function I have:

function checkTime() {  
  var current = new Date();
  var target = new Date('April 10, 2017 12:11:00');

  if (current < target) {
    $('#modalnew').modal('show');
  } else {
    window.location.replace('https://www.example.php');
  }
}

The function works as expected, but the date comparison logic is puzzling me. Despite looking at similar examples online, I'm still unable to grasp it fully. For instance, consider this hypothetical situation without any code:

Current Time (now) = April 10, 2017 12:22:00
Target Time (date set) = April 10, 2017 12:11:00

Given that current seems to be 11 minutes ahead of target, why does the function trigger the window.location? It appears illogical based on the time values alone. What exactly is being compared in this scenario?

Answer №1

When examining your scenario, it becomes apparent that d1 is actually greater than d2, contrary to what was expected. As a result, the code for window.location.replace is triggered.

During the comparison of the dates, the condition being evaluated is (d1.valueOf() < d2.valueOf()). The method valueOf() returns the time in milliseconds since the start of

00:00:00 UTC Thursday 1, January 1970
, which is then used for the comparison.

Answer №2

When comparing two dates in JavaScript, it is recommended to utilize the Date.prototype.getTime() method. This method returns a numeric value representing the time for the specified date based on universal time.

The numerical result obtained from comparing the values of dates d1 and d2 will determine which date is earlier or later.

Example code:

function checkTime() {  
  var d1 = new Date();
  var d2 = new Date('April 10, 2017 12:11:00');

  if (d1.getTime() < d2.getTime()) {
    $('#modalnew').modal('show');
  } else {
    window.location.replace('https://www.example.php');
  }
}

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

Modify the class of the dropdown and heading 2 elements if they meet specific conditions using Animate.css

Is it possible to add a class using jQuery when two specific conditions are met? 1) If the dropdown selection is either "acting" or "backstage" 2) If the membership status is set to "Non-member" If both of these requirements are fulfilled, I would like ...

"Enhance Your Browse experience: Chrome Extension that automatically appends content to pages

I'm currently developing a Chrome extension that detects when a URL on a specific domain changes, and if the URL matches a certain pattern, it will add new HTML content to the webpage. Here is an excerpt from my manifest.json file: { "name": "Ap ...

Tips for presenting hierarchical information from my database in ejs

I'm currently working on a genealogy application using node js express and ejs but I'm facing an issue with displaying the database in order (starting from parent). This is the code snippet for retrieving my data and what I see when I log the ou ...

Setting the outcome of an Ajax call as a global variable in JavaScript

I have a method that uses AJAX to request data and returns a JSON string containing Tokens records. I am trying to store this result in a global variable named 'tokens' so I can access it in other functions. After assigning the result to the &ap ...

Modifying variable assignments in an Angular index.html file according to the environment

Is it possible to dynamically set the config.apiKey value in Angular based on different environments such as Development and Production? In a Production environment, use config.appKey = 'AB-AAB-AAB-MPR'; In a Development environment, use config ...

"Exploring the process of assigning input data to a different variable within a Vue component

Reviewing the code snippet I currently have: <template> <div> <input v-model.number="money"> <p>{{ money }}</p> </div> </template> <script> name: 'MyComponent', data () { ...

Submitting a form is disabled when there are multiple React form inputs

I have a simple code example that is working correctly as expected. You can check it out here: https://jsfiddle.net/x1suxu9h/ var Hello = React.createClass({ getInitialState: function() { return { msg: '' } }, onSubmit: function(e) { ...

What is special about this element, textarea?

Hey there, I've got this JavaScript code that currently works on all textarea elements on the site. However, I'd like it to only work on one specific element. function limits(obj, limit) { var text = $(obj).val(); var str_length = $(obj) ...

Closing a dropdown menu when opening another one

As a beginner in Vue.js, I am currently working on a CRUD project for my coursework. One issue I am facing is with the behavior of the dropdown menu. Can anyone provide assistance? I have specific requirements: The dropdown menu without an active state ...

When trying to use bootbox.confirm within a dynamically loaded AJAX div, the modal unexpectedly opens and

I have implemented bootbox into my project, which was downloaded from . user_update.php is being loaded in a div within users.php using ajax functionality. Within user_update.php, there is a JavaScript function called validateForm(). Right after the functi ...

Acquire JSON data from a URL and display it on the webpage

I'm facing an issue where the JSON data I'm trying to fetch from a URL is not displaying due to an uncaught reference error in my code. How can I modify the code to ensure that the data gets shown? var url = "https://fantasy.premierleague.com/ ...

Encountering a Nuxt error where properties of null are being attempted to be read, specifically the 'addEventListener' property. As a result, both the default

Currently, I am utilizing nuxt.js along with vuesax as my UI framework. I made particular adjustments to my default.vue file located in the /layouts directory by incorporating a basic navbar template example from vuesax. Subsequently, I employed @nuxtjs/ ...

Help me figure out how to independently toggle submenus on my navbar by utilizing the Vue.js composition API

I am currently working on developing a navbar using the Vue.js composition API. My primary objective is to toggle the submenus when a user clicks on them. However, since I am iterating through an object to display the submenus, I am faced with the challeng ...

Guide to linking an external URL with a lightbox image

I have created a gallery and an admin gallery page. In the admin gallery, there is a delete button that appears over the image. However, when I click on it, instead of showing the message "Are you sure?", it opens a lightbox. I suspect that the code for t ...

Attempting to serialize a form using Ajax and jQuery

I am facing an issue with submitting user input from a modal using jQuery and AJAX. The problem is that the AJAX call is not capturing the user input. Even though the AJAX call is successful, when I check on the server side, the user input appears to be bl ...

Can the Route be modified in Next.js?

I have developed search functionality that navigates to "/search/xxxx", but it is located in the header. Every time I perform a search, the route gets repeated and becomes "/search/search/xxx". Could you suggest any way other than usin ...

Utilizing Node Js for Form Data Transmission and Retrieval

I've successfully created two separate JS files, each responsible for sending and retrieving form data to and from the database. My dilemma is whether it's more practical or feasible to leave these two JS files as they are and serve their individ ...

Updating switch data on click using Vuejs: A step-by-step guide

Could someone please explain to me how to swap two different sets of data when clicked? For instance, let's say we have the following data: data() { return { data_one: [ { name: "Simo", ...

Daily loop countdown timer

Looking to implement a daily countdown timer that ends at 10am, I have the following code set up: setInterval(function time(){ var d = new Date(); var hours = 09 - d.getHours(); var min = 60 - d.getMinutes(); if((min + '').length == 1){ ...

The Vue computed property is failing to retrieve the data it needs

I'm having trouble with the computed() property not retrieving data. Data was initialized in the created() property. Am I missing something here? Any guidance on how to resolve this issue would be greatly appreciated. const randomPlayers = { temp ...