check if a string could be a date too, like 2.1.24 in javascript

You can check if a string could be a date by attempting to create a Date object from it and then checking if the date object is valid. You can use the following code snippet in JavaScript to achieve this:

index.tsx
function isValidDate(dateString) {
    const date = new Date(dateString);
  
    // Check if the date object is valid
    return !isNaN(date.getTime());
}

const dateString = '2.1.24';
if (isValidDate(dateString)) {
    console.log('Valid date');
} else {
    console.log('Invalid date');
}
291 chars
14 lines

This function will return true if the string could represent a valid date and false if it could not be a valid date.

related categories

gistlibby LogSnag