JavaScript code often contains dates that are formatted in various ways

I need to perform validation in JavaScript by comparing DATES and TIME.

I need to have the date in dd/MM/yyyy format, but I am unsure of the format it is currently taking. After debugging the JavaScript code, I discovered the format. The screenshot below shows a different date than the one I am inserting as TODAYS date.

https://i.sstatic.net/OMlw0.png

Below is the code snippet:-

function ValidateRecord() {
        var StrPriError = "";

        if (document.getElementById('TextBox1').value == "" || document.getElementById('TextBox2').value == "" || document.getElementById('TextBox3').value == "" || document.getElementById('TextBox4').value == "") {
            StrPriError += "Dates cannot be blank \n";
        }
        else {
            var dt1 = new Date(document.getElementById('TextBox1').value + " " + document.getElementById('DrpTime').value);
            var dt2 = new Date(document.getElementById('TextBox2').value + " " + document.getElementById('DrpTime3').value);
            var dt3 = new Date(document.getElementById('TextBox3').value + " " + document.getElementById('DrpTime4').value);
            var dt4 = new Date(document.getElementById('TextBox4').value + " " + document.getElementById('DrpTime5').value);

            if (dt1.getTime() == dt2.getTime() || dt1.getTime() == dt3.getTime() || dt1.getTime() == dt4.getTime() || dt2.getTime() == dt3.getTime() || dt2.getTime() == dt4.getTime() || dt3.getTime() == dt4.getTime()) {
                StrPriError += "Dates and Times cannot be the same \n";
            }
            else {
               // StrPriError += "Good to go \n";
            }

            if (dt2.getTime() < dt1.getTime()) {
                StrPriError += "Reminder 2 cannot be less than reminder 1 \n";
            }

            if (dt3.getTime() < dt1.getTime()) {
                StrPriError += "Reminder 3 cannot be less than reminder 1 \n";
            }

            if (dt4.getTime() < dt1.getTime()) {
                StrPriError += "Reminder 4 cannot be less than reminder 1 \n";
            }
            if (dt3.getTime() < dt2.getTime()) {
                StrPriError += "Reminder 3 cannot be less than reminder 2 \n";
            }

            if(dt4.getTime() < dt2.getTime()) {
                StrPriError += "Reminder 4 cannot be less than reminder 2 \n";
            }

            if (dt4.getTime() < dt3.getTime()) {
                StrPriError += "Reminder 4 cannot be less than reminder 3 \n";
            }
        }
        if (StrPriError != "") {
            alert(StrPriError);
            return false;
        }
        else {
            return true;
        }
    }

Additionally, here is the associated HTML:-

<td colspan="1px" style="width: 13%" class="field">
                <asp:TextBox ID="TextBox1" runat="server" Width="80" Enabled="false"></asp:TextBox>
                <cc3:Calendar ID="Calendar1" runat="server" DatePickerMode="true" TextBoxId="TextBox1"
                    DatePickerImagePath="../../Images/icon2.gif" CultureName="en-GB">
                </cc3:Calendar>
                <asp:DropDownList ID="DrpTime" runat="server" Width="65px">
                    <asp:ListItem Value="09:00">09:00</asp:ListItem>
                    <asp:ListItem Value="13:00">13:00</asp:ListItem>
                    <asp:ListItem Value="17:00">17:00</asp:ListItem>
                    <asp:ListItem Value="21:00">21:00</asp:ListItem>
                </asp:DropDownList>
            </td>
            <td colspan="1px" style="width: 13%" class="field">
                <asp:TextBox ID="TextBox2" runat="server" Width="80" Enabled="false"></asp:TextBox>
                <cc3:Calendar ID="Calendar2" runat="server" DatePickerMode="true" TextBoxId="TextBox2"
                    DatePickerImagePath="../../Images/icon2.gif" CultureName="en-GB">
                </cc3:Calendar>
                <asp:DropDownList ID="DrpTime3" runat="server" Width="65px">
                    <asp:ListItem Value="09:00">09:00</asp:ListItem>
                    <asp:ListItem Value="13:00">13:00</asp:ListItem>
                    <asp:ListItem Value="17:00">17:00</asp:ListItem>
                    <asp:ListItem Value="21:00">21:00</asp:ListItem>
                </asp:DropDownList>
            </td>

This issue is preventing me from properly validating. Any suggestions on how to resolve this?

Answer №1

To accomplish this task effortlessly, employ moment.js.

let datetime = moment(document.getElementById('TextBox1').value + " " + document.getElementById('DrpTime').value, "DD/MM/yyyy HH:mm");

Answer №2

  const months = [
                       "January", "February", "March",
                       "April", "May", "June", "July",
                       "August", "September", "October",
                       "November", "December"
                       ];

                const date =  new Date(document.getElementById('TextBox1').value + " " + document.getElementById('DrpTime').value);

                output.value = date.getDate() + ' ' + months[date.getMonth()] + ' ' + date.getFullYear() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();

I believe the code above will be beneficial for you.

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

Order the results by a predicate chosen by the user and a predefined secondary attribute

Trying to organize a table of results by a user selected criterion and then by a predefined secondary one. For instance, the ng-repeat setup looks like this: <tr ng-repeat="line in model.resultList | orderBy:['-predicate', 'secondary_va ...

What is the best way to transform an array of objects into a nested array through shuffling

I am dealing with a diverse array of objects, each structured in a specific way: data = [ { content: { ..., depth: 1 }, subContent: [] }, { content: { ..., depth: 2 ...

display alternative text before an image is loaded on the screen

Is there a way to display text instead of an image before the image loads? I have a website with an image as the title, causing the page to load fully before the title image is loaded later. Is there a solution for this issue? ...

Developing a React Native app using Expo and Firebase? Learn how to prevent Firebase details from

I have encountered a problem with my code while working on the user edit profile page in my react native app. The issue I am facing is related to displaying the previously inputted firebase details from the collection in the text input fields when the user ...

Is there a method to give a webpage a subtle shimmering effect without utilizing CSS box-shadow?

Struggling to Develop a High-Performance Interface Feature I'm currently facing a challenge in coding an interface that requires a subtle and broad glow effect, similar to the example provided below: https://i.sstatic.net/E4ilD.jpg Exploration of ...

Extracting every other value from an array can be achieved by iterating through the

Hi, I'm looking to create a function that will log every other value from an array. For example, if we have: var myArray = [1,45,65,98,321,8578,'orange','onion']; I want the console.log output to be 45, 98, 8578, onion... Does ...

The script fails to start using npm start, however, it runs smoothly when using node server.js

For a while now, I've been facing an issue that I just can't seem to resolve. When I navigate to my project's src folder and execute `node server.js`, everything functions as expected. I can access the application at http://localhost:3000/cl ...

Jquery submenu accordion toggles open and closed with each click

My website has a hamburger menu with an accordion-style submenu implemented using jQuery for devices 1084px and smaller. For larger devices, the menu utilizes a hover-style submenu on desktop. However, I encountered issues when trying to use both the hove ...

Exploring Multilingual Autocomplete or: Best Practices for Managing Multiple Languages in Web Applications

I'm currently developing a website and I have a mysql-table named 'items' with the following structure: item_id | item (The second column is used to identify the item_id.) In a file called language1.php, I have an array that stores the it ...

Struggling to access the height attribute from a CSS file

Hey there. I'm pretty confident that the solution to my query is quite simple. So, I have a .css file with this particular code snippet: div.site { text-align:center; border:2px solid #4b6c9e; padding:1px; margin-top:10px; font-size:medi ...

Issue with PHP's ng-click not functioning properly with Angular JS's dynamic HTML generation

I'm just starting out with Angular JS. I'm trying to create an ng-click event in dynamically generated HTML from PHP, here's the code snippet. var app = angular.module('pageapp',[]); angular.module('pageapp') .filter(& ...

To modify the text within the pagination select box in ANTD, follow these steps:

Is it possible to modify the text within the ant design pagination select component? I have not been able to find a solution in the documentation. I specifically want to replace the word "page" with another term: https://i.sstatic.net/w55hf.png ...

Unable to modify information retrieved from API. Error: Unable to assign to property that is set to read-only

Using an API call, I retrieve some data. getPosts(postRequest: PostRequest): void { this._postService.getPosts(postRequest).subscribe(result => { const postList = result as PostList this.posts = postList.posts }); ...

retrieve the value of a specific key using JSON stringify

[{"displayorder":"1","menuname":"DashBoard","menuid":"5","menuurl":"dashboard.php"},{"displayorder":"3","menuname":"Accounting Module","menuid":"3","menuurl":""},{"displayorder":"4","menuname":"My Profile","menuid":"4","menuurl":"myprofile.php"},{"displayo ...

I am looking to implement an animation that automatically scrolls to the bottom of a scrollable DIV when the page is loaded

My DIV is configured with overflow-y set to scroll. .scrolling-div { width: 85%; height: 200px; overflow-y: scroll; } If I have an abundance of content within this div, my goal is for it to automatically scroll to the bottom upon loading the page. I am ...

Raspberry Pi 4: My LED is only blinking 8 times instead of the expected 16 times

I have encountered an issue with my program run, compilation, and result. In the screenshot below, you can see that my LED is only blinking 8 times instead of the anticipated 16 times. My expectation was for the LED to blink every 0.25 seconds for a total ...

Setting the x-api-key header with HttpInterceptor in Angular 4: A guide

I am attempting to use HttpInterceptor to set the header key and value, but I am encountering the following error: Failed to load https://example.com/api/agency: Response to preflight request doesn't pass access control check: No 'Access ...

What is the best way to retrieve the value from a textarea and verify if it is blank or not?

I have successfully incorporated a textarea using simpleMde, but I am facing difficulty in retrieving the value and checking whether it is empty or not. var message = document.getElementById("simpleMde").value; console.log(message); <textarea class=" ...

Next.js 14 useEffect firing twice upon page load

Having an issue with a client component in next js that is calling an API twice at page load using useEffect. Here's the code for the client component: 'use client'; import { useState, useEffect } from 'react'; import { useInView ...

The logo marquee unexpectedly bounces up and down at the end of every

Struggling with a JavaScript code issue. The Logo marquee suddenly jumps at the end of each loop: I've tried everything, but I can't seem to fix it and make it work as intended Here's the complete script that technically works, but causes ...