skip to Main Content

We are using react, what we are trying to achieve is:
Basically I get an array of objects where every object has 60 properties, and all of them are dynamic , I mean we are not aware what data it will have. we are only sure about that it will be a string value, and if any string value is date we want to show in particular format(MM/DD/YY HH:MM AM/PM), if it is not a date we want to show it as it is.

I saw so many similar questions are already answered and they are suggesting to use Date.Parse("iputstring") or new Date("inputstring") but it is not helping me because in my case input string can be anything eg. "0", "10", "10/10/2023" , "ASB" etc.

And when string like "0" is passed to Date.Parse or new Date it doesn’t say it is not date instead Date.Parse giving me a timestamp and new Date giving me default date.

Which I don’t want, I want’ to be 100% sure that input string is date.

Please guide me on this, thanks in advance.

2

Answers


  1. you can use the moment js library to validate date strings in JavaScript

    eg.

    const dateString = "07/05/2023";
    
    const momentObj= moment(dateString);
    
    const isValid = momentObj.isValid();
    
    if (isValid) {
      console.log("The date string is valid.");
    } else {
      console.log("The date string is invalid.");
    }
    
    Login or Signup to reply.
  2. By using a function like this you can validate if it is a date or a not,

    function isValidDate(inputString) {
      const date = new Date(inputString);
      
      // Check valid date and not NaN
      if (isNaN(date)) {
        return false;
      }
      
      //ensure the date format is MM/DD/YY HH:MM AM/PM
      const formattedDate = date.toLocaleString('en-US', {
        month: '2-digit',
        day: '2-digit',
        year: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        hour12: true
      });
    
      return formattedDate === inputString;
    }
    
    
    console.log(isValidDate('15/07/2023')); 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search