Format Date

    0

    1

    pkmooj

    This function will return a formatted date string for the given input date. The date string will be based off of the date object, which will have the date's date, day, month, and year. The function will then replace the given pieces of the date with the appropriate values according to the format string.

    Library: react

    const dateFormat = (inputDate, format) => {
      //parse the input date
      const date = new Date(inputDate);
    
      //extract the parts of the date
      const day = date.getDate();
      const month = date.getMonth() + 1;
      const year = date.getFullYear();
    
      //replace the month
      format = format.replace("MM", month.toString().padStart(2, "0"));
    
      //replace the year
      if (format.indexOf("yyyy") > -1) {
        format = format.replace("yyyy", year.toString());
      } else if (format.indexOf("yy") > -1) {
        format = format.replace("yy", year.toString().substr(2, 2));
      }
    
      //replace the day
      format = format.replace("dd", day.toString().padStart(2, "0"));
    
      return format;
    }
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.