The startdate and enddate functionality is experiencing issues when transitioning into a new year

I have implemented a datepicker for the startdate and end date in my project with the following code snippet:

       <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
          <script src="//code.jquery.com/jquery-1.10.2.js"></script>
          <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
          <link rel="stylesheet" href="/resources/demos/style.css">
          <script type="text/javascript">
          $(function () {
                $( "#startDate" ).datepicker({
                      changeMonth: true,
                      changeYear: true,
                      dateFormat: 'dd-mm-yy'
                    });

                $( "#endDate" ).datepicker({
                      changeMonth: true,
                      changeYear: true,
                      dateFormat: 'dd-mm-yy'
                    });
            });
          </script>
         <style type="text/css">
                .search_textbx
        {
         background-image:url('/SalesPropeller/calendar.jpg');
            background-repeat:no-repeat;
           background-position:right;  

        }
                </style>
    <form name="form" action="quotationSearchResult.jsp" method="post">
     <input type="text" id="startDate" name="startDate" class="search_textbx" readonly="readonly" placeholder="&nbsp &nbsp dd-mm-yyyy"/> 
      <input type="text" id="endDate" name="endDate" class="search_textbx" readonly="readonly" placeholder="&nbsp &nbsp dd-mm-yyyy"/></td>
</form>

In the quotationSearchResult.jsp file, I am fetching search results based on certain criteria.

<div id="divRight">
                &nbsp;
                <%
                    int count = 0;
                    int SlNo=1;
                %>
                <hr />
                <h3>Search Result for <u><%= request.getParameter("companyName")%></u> is : </h3>
                <hr/>
                <div id="divtable_wrapper">
                    <div id="divtbody" style="height: 470px;">
                        <form method="post" name="form">
                            <table class="divtable" width="1140">
                                <div id="divheader">
                                    <thead>
                                        <tr>
                                           <!-- Table headings -->
                                        </tr>
                                    </thead>
                                </div>

                                <%
                                    // Java SQL query and result processing logic
                                %>

                                <%
                                    while (rs.next()) {
                                %>
                                <tr>
                                   <!-- Display data from database -->
                                </tr>
                                <%
                                    }
                                %>
                                <%
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                %>
                            </table>
                        </form>
                        <br>
                        <span style="float: left;"> &nbsp;<b><%= count%></b> Search Result Found.</span>
                <br><br>
                </div>
                </div>
                 </div>

Upon testing with different start and end dates, I noticed discrepancies in the comparison results which you can see in these images: https://i.sstatic.net/2WduJ.png https://i.sstatic.net/9bFQ6.png However, when using different dates like "07-12-2015" and "18-01-2016", the records are not being fetched as expected: https://i.sstatic.net/cKQDc.png https://i.sstatic.net/A5mmL.png

This issue seems to be related to comparing years properly in the SQL database backend. https://i.sstatic.net/GAHIa.png

Answer №1

The issue at hand lies within the column "Date" being stored as a varchar. It is imperative to store dates in the correct format, which should be Date, and "Date" is not an ideal name for a column due to it conflicting with a MySQL function.

Storing dates as strings results in them being unsortable, as shown below:

  1. 07-01-2016

  2. 07-12-2015

  3. 18-01-2016

For instance, 07-01-2016 falls outside the range of 07-12-2015 and 18-01-2016

The most effective solution would be to convert the column format to the appropriate Date format in the database.

If immediate conversion is not feasible, a temporary fix involves converting the String column to date and adjusting the search string's formatting to align with MySQL syntax

//convert search string to mysql format (note you can define variables for faster code and you should consider handling exceptions)
startDate = new SimpleDateFormat("yyyy-mm-dd").format(new SimpleDateFormat("dd/mm/yyyy").parse(startDate));
endDate = new SimpleDateFormat("yyyy-mm-dd").format(new SimpleDateFormat("dd/mm/yyyy").parse(endDate));

//syntax for query
... AND STR_TO_DATE(`Date`, '%d/%m/%Y') BETWEEN '"+startDate+"' AND '"+endDate+"';"

Further guidance can be found in these resources:

how to convert a string to date in mysql?

How do I query between two dates using MySQL?

Utilizing Prepared statement is also recommended to mitigate sql injection risks.

Avoiding SQL Injection

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

CSS Styles Not Sticking in Jquery

Hello everyone! I'm new here and I need some help. I want to change the background of a td element without losing the CSS styling that is currently applied to it. Right now, the background is repeating and tiling. Below is the script I am using: $ ...

Error message "Assignment operation cannot occur on the left side" occurs when attempting to use the NOT operator

Currently, I have this function in use: $scope.myFunction = function(indexParent, childrenLength) { // close all inner accordion tabs for(i=0; i < childrenLength; i++) { !$scope.lettersandnumbers[indexParent].things[i].open = $scope.le ...

Implement 2 new search options into the datatable plugin

Looking to enhance my existing panel by adding 2 search options: Here are the credentials you'll need: username: admin pass: Nopass1234 The additional features I want to include are: 2 search options: 1. from date 2. to date What will happen w ...

The setValue change function in Bootstrap-slider.js does not get triggered when called programmatically

I've incorporated bootstrap-slider.js into my project and everything seems to be working smoothly. However, I've encountered an issue with setting a new value using the setValue function, as it does not seem to trigger the associated "change" fun ...

Steps to define a Java bean for the given JSON structure

I am facing a challenge with the JSON response from a webservice. The inner object name, which is dynamic, is causing confusion for me. I am struggling to figure out how to declare an equivalent Java bean for this situation... { "error": [ { ...

Move upwards and move downwards

I have a list of groups with names. <ul id="groups" > <li id="group1" ></li> <li id="group2" ></li> <li id="group3"></li> </ul> Additionally, I have sliding containers. <div id="containers" > ...

Divide a compound element of TextNodes and elements by utilizing jQuery

Looking for a way to split an HTML element based on user selection using jQuery? Check out the example below with square brackets indicating the selection: Lor[em <a>ips]um <span>dolor</span></a> The desired output should be: Lor ...

Update the objects with new values when the user makes changes in the

I am working with dynamically created input fields const [data, setData] = useState({ native: [{}], rolls: [{}] }) // initial data {navtive?.map((item, index) => { return ( <input type="text" name={item.id} ...

What is the proper method for adding a file to formData prior to sending it to the server using a

I came across this tutorial on FormData, but I'm still trying to grasp how the formData object functions. Input Form Example: https://i.stack.imgur.com/h5Ubz.png <input type="file" id="file-id" class="w300px rounded4px" name="file" placeholder=" ...

Guide on retrieving information from mongodb with nodejs and expressjs

Check out my code in the file named student.js var mongoose = require('mongoose'); var studentSchema = new mongoose.Schema({ name:{ type: String, required: true }, rollno:{ type: Number, required: tr ...

Using the set() method in Firestore with the merge option does not function properly when implemented in Node.js

const user = {name : myUsername}; databaseRef.set(user, { merge: true }); An error is occurring which states: Invalid use of type "undefined" as a Firestore argument. Despite following the Firebase documentation here, and seeing others use it in online ...

Methods to merge two click functions, one of which includes a conditional statement based on window size

I'm looking to streamline my code by combining two click functions. Can anyone provide guidance on how to do this effectively? Thank you! $(document).ready(function () { //when clicking on a link hide the navigation links $('nav a').click ...

Guide on creating a hover-based side menu

I am looking to enhance the sub-menus like PRODUCT 1, PRODUCT 2, etc. by adding side menus that appear when hovering over them. Can anyone assist with implementing this feature in the code below? Below is the current code snippet: CSS: @import url(http: ...

Highcharts: generating numerous series utilizing JSON dataset

I am struggling to generate a chart with multiple series using JSON data. Although I have successfully created one with a single series, it doesn't look right and the legend is missing. I need guidance on how to rectify this issue. Currently, I only h ...

I'm experiencing an issue where the submit button on my HTML form is not successfully recording my information

Welcome and thank you for taking the time to read this. I am facing an issue while setting up a login system. For styling purposes, I had to create two separate forms: one for Email and Password, and another for the submit button. Unfortunately, because ...

Ways to eliminate a specific array from another array using JavaScript

0: {id: 1553825061863, name: "Thai Milk Tea", qty: "1", total_amount: 9500, toppings: 500, …} 1: {id: 1553825061863, name: "Thai Milk Tea", qty: "1", total_amount: 9500, toppings: 500, …} 2: {id: 1553825061863, name: "Thai Milk Tea", qty: "1", total_am ...

Uh oh! There seems to be an issue with the ClerkJS frontendAPI option. Visit the homepage at https://dashboard.clerk.dev to retrieve your unique Frontend API value

Despite inputting the correct Clerk API keys, I'm encountering issues with the functionality of the ClerkJS API. I anticipate that the application should enable me to utilize the ClerkJS API for user authentication without any problems. ...

Why is it not possible to display the browser version with JQuery 2?

I'm fairly new to JavaScript and JQuery and I'm facing a specific issue. After including JQuery 2.1.4, my goal is to create a simple JQuery script that displays the browser name and its version. Following this tutorial on the official documenta ...

Currently, I am utilizing datastage to transfer information from one column to another

The code snippet I utilized is: Trim(IF FromDataSource.PID_VALID = 'Y' THEN FromDataSource.Person_ID ELSE @NULL) ...

Adjust the audio volume by using an HTML range input element

I am currently facing issues while using the HTML range element to adjust the volume of an HTML audio element. In another instance on this site, I came across a one-line setVolume function that seemed to work, but now I am encountering an error ("Uncaught ...