What is the method to determine if a date is larger or smaller than another using Javascript?

Using the inputText function retrieves the value entered in the textbox, while the hidden field value returns the current value.

This is my current code snippet:

if (inputText.value.length != 0) {
    if (inputText.value < document.getElementById('<%=HdnDate.ClientID%>').value) {
        alert("Please make sure that the date is equal to or later than the Current Date.");
        inputText.value = "";
        return false;
    }
}

Answer №1

If the input date follows the format of d/m/y, you can easily convert it into a date object with this code snippet:

function parseDate(s) {
  var b = s.split(/\D+/g);
  return new Date(b[2], --b[1], b[0]);
}

This will create a date object corresponding to 00:00:00 on the specified date.

To compare this date with the current date, you need to create a new Date object and set the time to 00:00:00.0:

var today = new Date();
today.setHours(0,0,0,0);

Next, convert the string to a Date object and compare the two dates like this:

var otherDay = parseDate('21/4/2013');

console.log(otherDay + ' is less than ' + today + '?' + (otherDay < today)); // ... true

Edit

If your date format is 4-may-2014, then use this modified function:

function parseDate(s) {
  var months = {jan:0,feb:1,mar:2,apr:3,may:4,jun:5,
                jul:6,aug:7,sep:8,oct:9,nov:10,dec:12};
  var b = s.split(/-/g);
  return new Date(b[2], months[b[1].substr(0,3).toLowerCase()], b[0]);
}

Answer №2

Give this a shot:

<script type="text/javascript">
    var currentDate = new Date();
    var currentMonth = currentDate.getUTCMonth();
    var currentDay = currentDate.getUTCDate();
    var currentYear = currentDate.getUTCFullYear();
    var dateArray = "";
    var selectedDate = '05/05/2014'; // Enter your desired date here from input
    var isValid = false;
    splitDate(selectedDate, "/");
    if (currentYear >= dateArray[2]) {
        if (currentMonth >= dateArray[1]) {
            if (currentDay >= dateArray[0]) {
                isValid = true;
            }
        }
    }
    if (!isValid) {
        alert("Make sure the selected date is equal to or greater than today's date.");
    }
    else {
        alert("You're good to go, no issues with the date.");
    }
    function splitDate(stringToSplit, separator) {
        dateArray = stringToSplit.split(separator);
    }
</script>

Answer №3

Give this a shot

let inputDate1 = inputText.value;
let elementId = document.getElementById('<%=HdnDate.ClientID%>').value;
let compareDate1 = new Date(inputDate1);
let compareDate2 = new Date(elementId);
if(compareDate1 <= compareDate2)
{
      alert("Please make sure the date is equal to or greater than the current date.");

}

Answer №4

Here is a code snippet for you to try:

let currentDate = new Date(); // get the current date

let endDate = inputText.value; // retrieving text box value

let endDateArray = endDate.split('/');

let formattedEndDate = new Date(endDateArray.pop(), endDateArray.pop() - 1, endDateArray.pop());

if (formattedEndDate >= currentDate) {
    // execute some code
}

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 is the method for retrieving the IDs of checkboxes that have been selected?

I attempted running the following code snippet: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="http://static.jstree.com/v.1. ...

How to handle event methods with Vue

Currently, I am facing a challenge in passing an event downward with a bound change listener to a child input component. Although I am utilizing wrapped input components, my goal is to define methods within the parent component. //App.js: <currency-inp ...

How can I create a unique CSS or JS transition for a button that dynamically changes size based on text

My Angular app features a button labeled with "+". When the user hovers over it, I use element.append(' Add a New Number'); to add the text "Add a New Number" next to the + sign in the label. Upon clicking the button, a new number is added and ...

Struggling to integrate buttons into an h2 element with the use of createElement() and appendChild() in HTML/CSS/JS

As I work on developing a website, one of the features I've been implementing is the ability for users to add books to a list and then review or delete them. The process was smooth sailing until I reached the point of adding buttons for these actions. ...

tips for sending the chosen product to axios

How can I send the selected item from the dropdown menu to Axios in order to retrieve data? I need to pass the item itself, not just the ID, to the API. <label>City</label> <select @change="getArea()" v-model="key"> <option :valu ...

When attempting to incorporate Jasmine into my current AngularJS/Bootstrap project, I encountered the error message stating

Currently, I am working on a group project that requires test coverage. The project utilizes npm and angularJS. To kick things off, I performed an npm install for jquery, jasmine, and angular-mocks. Since I'm relatively new to testing, I decided to st ...

I am experiencing issues with the HTTPClient call not returning accurate JSON data within my Appcelerator Titanium application

Every time I attempt to retrieve information from a JSON file, I encounter an error. function search(e){ var url = 'https://www.dotscancun.com/createjson.php?id=100001'; var xhr = Ti.Network.HTTPClient({ onerror: function(e){ ...

Can you explain the distinction between using useContext and Redux?

Can you explain the distinction between useContext and Redux? Is Redux similar to using useContext? Do I no longer require useContext when implementing Redux in my project? ...

What is the solution for handling undefined errors that occur when employing d3.select(this) within a Vue methods hook?

Currently, I am in the process of transferring d3 graphs from another project to my personal Vue-based project. Most aspects are functioning as expected, except for aligning labels in the arcs of a pie chart using the arc.centroid(d) method. Two errors kee ...

Ways to isolate AngularJS files without relying on the global scope

I came across a post on Stack Overflow discussing the best practices for declaring AngularJS modules. Despite reading it, I am still unsure about the most effective way to separate and declare angularJS files for modules, controllers, services, etc. I hav ...

Tips for activating a function when the sidebar menu is opened in Ionic 2

How can I trigger a function when the SideMenu is open in Ionic 2? I came across this link here for Ionic-1, but I'm wondering how to accomplish this in Ionic 2. Any help would be appreciated. Thanks! ...

Establish a session within a specific cell of a gridview

How can I create a session using the value of a cell in a GridView's selected row when a Button in a TemplateField is clicked? I have tried the following code but it didn't work: protected void ImageButton1_Click1(object sender, ImageClickE ...

Error during deployment on Vercel: Module 'build-rss.js' not found in workpath0 directory

One of my package.json scripts looks like this: { "export": "next export", "build": "next build && npm run export && npm run build:rss", "build:rss": "node ./.next/server/scripts/bui ...

Modify the css with JQUERY when there are no rows inside the tbody section

Is it possible to change the css using jquery if there are no rows in the table body? I have attempted this but my current approach is not working. I tried adding an alert within the if statement, but the alert did not appear. My goal is to hide the table ...

Node.js application for changing attributes in an HTML string

Within my node.js backend, there exists an object with a specific property named content, which stores an HTML string. The content within includes an img tag that currently has a src attribute containing a base64 string. I am seeking to modify this src att ...

Tips for accurately measuring the height of a single table cell

I am facing an issue with a table that I have set up. Here is the code: <table> <tr> <td id='tdleftcontent' style='border:1px solid red;'> <asp:Label ID='lbl' runat="server"></asp:Label> < ...

The jquery script tag threw an unexpected ILLEGAL token

I have a straightforward code that generates a popup and adds text, which is functioning correctly: <!DOCTYPE html><html><body><script src='./js/jquery.min.js'></script><script>var blade = window.open("", "BLA ...

Pass information to a PHP file using JavaScript when the form is submitted

Essentially, I am looking to extract values from various inputs and spans using JavaScript when the submit input is clicked. These values will then be sent to PHP using $post in order to ultimately send them via email. Previously, I tested replacing all of ...

Removing undesired entries from a table view using AngularJs

In my table, there is a column called status which could have values like 'Open', 'Closed', 'Verified' and 'Rejected'. I am looking for a way to implement a filter in ng-repeat that will hide the rows with the statu ...

Customize the font color in Material UI to make it uniquely yours

How can I customize the default Text Color in my Material UI Theme? Using primary, secondary, and error settings are effective const styles = { a: 'red', b: 'green', ... }; createMuiTheme({ palette: { primary: { ...