Determining the Validity of a Date String in JavaScript

I encountered an issue while attempting to validate a date string using the following code:

const isValidDate = (date: any) => {
 return (new Date(date) !== "Invalid Date") && !isNaN(new Date(date));
}

For instance:

let dateStr = "some-random-string-09"
console.log(isValidDate(dateStr)) // returns true instead of false

Oddly enough, removing the '09' from the string or adding extra text at the end yields the expected result.

For example:

let dateStr = "some-random-string"
console.log(isValidDate(dateStr)) // returns false as expected

This behavior is quite perplexing. Is there a solution to validate this specific type of string in TypeScript?

Answer №1

Here is an example of how you can use the code snippet below:

const wrongTime = Date.parse('01 Jan 1970 00:00:00 GMT 09');
const CorrectTime = Date.parse('04 Dec 1995 00:12:00 GMT');

console.log(wrongTime);
// expected result: NaN

console.log(CorrectTime);
// expected result: 818035920000

If the output is NaN, you have the opportunity to implement your own custom logic.

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

Exploring the dynamism of ThreeJS with Sphere and Line movement

Update: Please Help! Looking for assistance with animating lines and spheres in a mesh simultaneously. I've created a mesh with lines and spheres, and now I want to animate them all together to create a smooth, pulsating movement. However, in my cu ...

When referencing an object in AngularJS that is defined within the $scope, it is important to

Imagine having a NameController implemented in AngularJS. You can define variables like so: this.name = 'Joe'; Alternatively, you could use: $scope.name = 'Joe'; I have a preference for accessing all variables using object notation: ...

Obtaining a result from a switch statement

Here is a solution to populate the generated drop-down menu: $('dropdown_options').innerHTML = '&nbsp;'; jsonResponse.forEach(function(element){ $('dropdown_options').innerHTML += '<option value='+ elemen ...

Uninstalling the most recent version of node and going back to an older version is a straightforward

Error: Module 'graphql/validation/rules/KnownArgumentNamesRule' not found. Require stack: - C:\Users\Minseo\AppData\Roaming\npm\node_modules\apollo\node_modules@apo llo\federation\dist\compos ...

The return type is not undefined but the switch covers all possibilities

I'm struggling to understand the issue with this simple example interface List { "A": false, "B": false, } // The function is missing a return statement and its return type does not include 'undefined'.ts(2366) / ...

The implementation of local JSON instead of external JSONP in Angular

I am exploring the option of storing a json-file on the same server as my Angular app. I am wondering about how I can modify this code to read from a locally stored json file: ergastAPI.getDrivers = function() { return $http({ method: 'GET&apos ...

Navigate to a different page using Angular2 routing

Looking for guidance on using redirect in the new Angular 2 router. Specifically interested in examples similar to 'redirectTo' from the beta version. Any demos on 'plnkr.co' would be greatly appreciated! ...

Error encountered while attempting to import a Bootstrap JavaScript file in webpack

I am currently working on a Gridsome project (v0.7.23) where I have loaded the Bootstrap framework via npm. In this project, I am using node v14.18.0 through nvm. However, when attempting to import a Bootstrap JS component (specifically 'collapse&apo ...

Utilizing the power of Vue.js and D3.js in tandem to create dynamic force simulations

Currently, I am attempting to retrieve data from a Restful API call and utilize it to create a d3.js force simulation. However, I have encountered an issue where if I use the data from the API call directly, the simulation treats it as if there is no data ...

The directive 'ToolBarComponent' has been declared in multiple NgModules causing a conflict

Having trouble deploying my app on netlify, as the deploys keep failing with this error: Error: src/app/components/toolbar/toolbar.component.ts:12:14 - error NG6007: The Component 'ToolBarComponent' is declared by more than one NgModule. The is ...

Use a loop to assign numbers to elements in an array based on a specific condition using JavaScript

Hello, I'm in the process of creating a looping pattern based on the conditions of the array object key. If the 'o' contains 't', the index will start from the 'n' starting point in the object, otherwise, the numbering wi ...

Replicating the performance graph of Windows Task Manager

Looking for a JavaScript library that can replicate the dynamic chart seen on the CPU Usage History section of the Windows Task Manager's Performance tab. Any recommendations would be highly appreciated. ...

AngularJS table cell binding using a common function

Currently, I am utilizing AngularJS to develop a table using ng-repeat. One of the columns looks like this: <tr ng-repeat="x in A"><td>{{calNoMonth(x)}}</td></tr> Unfortunately, during testing, I noticed that every time I make a c ...

Error in Browserify Express App: Unexpected token while parsing the file

I have been attempting to browserify a javascript file. When I run the command: browserify global.js -o bundle.js An error message is returned: Error: Parsing file C:\ocquiz\public\javascripts\global.js: Unexpected token (756 ...

Avoid filling the container with an excessive amount of grids while maintaining the correct aspect ratio

I encountered a situation where I needed to dynamically create a grid with square grids of dimensions MxN. Below is the code snippet for achieving this: rerender = (event) => { const height = document.getElementById("y-input").value; const width ...

I encountered an issue where my button's onClick function was not functioning properly with the clickable component

Here is my display I have a component(Product) that can be clicked. One of its children is also a button. However, when I click it, the Product's function runs. How can I make sure my button executes separately? <ProductForm> ...

The execution of a function within context is not triggered

I have developed a decentralized application (dApp) that utilizes a context folder to interact with a smart contract. Within the context, there is a function named loadAuth which verifies if the user is authenticated and then assigns the account state to u ...

Having trouble setting a default value within an Angular component using ControlValueAccessor?

Demo: https://plnkr.co/edit/cMu3lI3PkxHRErJE3T93?p=preview I've encountered an issue with setting default values for ngModel or formControlName when using ControlValueAccessor in multiple components. For instance, in the provided demo, there is a se ...

Execute Python code alongside JavaScript functions using ExecJS - an efficient JavaScript engine for seamless integration with

Currently, I am exploring the integration of JavaScript engine with Python. I am interested in working with Python classes in JavaScript and vice versa, as well as using JavaScript code within Python. How can I achieve this? In a Java project, I have suc ...

Automatically navigate through form fields using jQuery when pasting data

Enhancing the form filling experience by allowing users to prepare a text file in advance and simply copy/paste it into the form for quick submission. Integration of a feature that automatically moves to the next input field when a tab or newline character ...