Confirm that the string is in the correct JavaScript Date format

I'm encountering an issue with validating the specified string obtained from the new Date() Object.

"2020-10-06T14:23:43.964Z"
. I anticipate receiving either this particular input format or a new Date(). My aim is to create something that can handle this scenario, similar to:

const checkDateValidity = (d: Date):boolean => {
 if (d instanceof Date || /* validate Date string here */) {
   return true
 }
 return false
}

Answer №1

Here is a helpful solution for you.

Date.prototype.checkValidity = function () { 
  // This function checks if the date object is valid by comparing the getTime() method
  // If it returns 'NaN', it means the date is invalid. 
     return this.getTime() === this.getTime(); 
};

Answer №2

After finding the second half of my issue in this post, which provides more detailed information about javascript regex iso datetime

The function I devised is intended to verify whether the input is a Date object instance or a string that matches the output of the Date object.

function checkDateValidity (input) {
  if (input instanceof Date) {
    return true;
  }
  return /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/.test(input) ? true : false
}

const date1 = new Date(); // true
const date2 = '2020-10-05'; // false
const date3 = '2020-10-06T14:23:43.964Z'; // true

console.log(checkDateValidity(date1))
console.log(checkDateValidity(date2))
console.log(checkDateValidity(date3))

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

Using the default theme in Material UI5

Could someone please explain how to pass in the default theme in Material UI5? In Material UI6, I used to do it like this: const useStyles = makeStyles((theme) => ({ home: { display: "flex", paddingTop: "8rem", width: ...

Verify the presence of a JSON object within the session storage using JavaScript

I'm currently developing a website where some data is stored within the session. In the initial page, I need to verify if the JSON object already exists in the session. Below is the code snippet that's causing issues: var passedTotal = JSON.par ...

Tips for showing outcome in the main window after form submission in a showModelDialog box through ajax

I find myself in a challenging situation where the parent window triggers a showModalDialog box to submit a form. Upon submission, the form is sent to a struts2 action which performs some tasks and then redirects back to the parent page, causing a full ref ...

Trouble with displaying points in Angular2's highcharts

I have implemented the angular2-highcharts chart module in my angular2 web application. Everything works fine when the graph has less than 7000 points, with the line and points displaying correctly. However, once the number of points surpasses 7000, there ...

"Discover the simplicity of customizing Bootstrap 5 with an easy-to-use online tool

When I was using Bootstrap 3, there was a convenient tool that allowed me to customize which features I wanted in the minified CSS/JS files to improve loading time. Now, as I delve into the documentation for Bootstrap 5, I find myself struggling to unders ...

In a Vue.js application, parameter passing does not function as intended

As someone who is new to JavaScript, I have a question regarding Vuex and creating a simple Todo Manager. I am facing an issue with deleting todos from my list and not getting the desired parameter (the id of the todo) in my actions. Here is the code snip ...

Invalid Media Type received following the request

I am trying to send a POST request from my Angular client to a Spring endpoint. Here is the endpoint in my HomeController: @RestController() public class HomeController { @PostMapping(value = "/payment/{unique_transaction_id}") public ResponseEnt ...

How about placing a particle on the top layer of a mesh at a random location?

I am struggling to place a particle on the top side of a custom mesh using Three.js. Most tutorials I've come across only demonstrate adding particles to cubes or spheres, leaving me with no solution for my unique shape. How can I successfully positio ...

Issue with FileStreamResult not triggering download prompt after AJAX call in MVC

I am encountering an issue with my code that is triggered by the "export" li tag. It converts a FusionChart to an SVG string and then sends it to my controller via an ajax call. The problem I'm facing is that even though the controller receives the r ...

Implementing additional states in an AngularJS app configuration with Ui-Router

Currently tackling a major application with numerous routes for its different components, my team and I have decided to break down the routes into separate files instead of cramming everything into one large file. In attempting to create a variable and im ...

Easy task tracker in Vue.js

I’m currently delving into the world of VueJS and working on a simple to-do list application. The issue I’m facing is that I can't seem to successfully pass an array to the child component responsible for displaying the list: Parent Component < ...

Why does jQuery treat an integer as a string when adding it to a variable?

While working on a for statement, I encountered an issue with adding an integer to a variable that increments. Strangely enough, the addition operation treats the integer as a string. However, other operations like subtraction or multiplication behave as e ...

Swipe to modify Array

Currently, I am in the process of developing an application that features a Swipe card interface using both AngularJS and the Ionic framework. The functionality of this app will be similar to the one found at . When swiping to accept a card, I want the ar ...

Learn how to store the outcomes of an HTTP operation within array.map() in JavaScript

Having read numerous articles, I am a complete beginner when it comes to async programming and struggling to grasp its concepts. My goal is to map a filtered array of objects and return the result of a function (an amount) to set as the value of pmtdue. De ...

Converting "require" to ES6 "import/export" syntax for Node modules

Looking to utilize the pokedex-promise for a pokemonapi, however, the documentation only provides examples on how to require it in vanilla JavaScript: npm install pokedex-promise-v2 --save var Pokedex = require('pokedex-promise-v2'); var P = new ...

Substitute the attributes of one object with those of another

Alright, I'm revising this because it seems to be causing confusion. Imagine you have two items x and y. What I aim to do is swap all the characteristics of x with those of y. (Please note that this isn't your usual duplication process where a ...

What are the best ways to personalize the Ant Design table and pagination component?

Is there a way to customize and design table and pagination components? Specifically, I am looking to set the header color of the table as green. How can this be achieved? Similarly, for the pagination component, I want to have a background color on page n ...

A pop-up box appears when hovering over a radio button

There are three radio button options available: None Float Left Float Right When the user hovers over the radio button, I want to show a preview of the div. <asp:radiobuttonlist runat="server" id="rbl" repeatdirection="Horizontal"> <asp:li ...

AngularJS Update Parent-Child Relationship: Enhancing the Details

When Panel header is clicked, I want to update the respective Panel body with the corresponding data. In my Angular code on Plunker, clicking "Test1" should only update "Test1detail" in the body. Click here for the Plunker Here's the code snippet fr ...

Having trouble deciphering the Enum definition in the Typescript Build

One of my projects utilizes a typescript package stored in npm with all the necessary definitions: index.d.ts export declare namespace OfferCraft { enum Country { es, it, fr, uk, de } enum Brand { ...