Search code examples
javascriptdatelocalization

Return the date format for date without moment.js


I can't figure out how to build a function that does this

INPUT: dateToDateFormat('16/07/2022') -> OUTPUT: DD/MM/YYYY

INPUT: dateToDateFormat('07/16/2022') -> OUTPUT: MM/DD/YYYY

The input dates will be already formatted by .toLocaleString function

Edit:

I think I was not precise enough with the output, it should literally output MM/DD/YYYY as a string, not the actual date value


Solution

  • A) First of all, your desired date string conversion seems to be easy (solution below) without using any package/overhead.

    B) However, if you need to process it further as a JS Date Object, things become more difficult. In this case, I like to provide some useful code snippets at least which might help you depending on your usecase is or what you are aiming for.

    A) CONVERSION

    Seems you need a simple swap of day and month in your date string? In this case, you do not need to install and import the overhead of a package such as date-fns, moment or day.js. You can use the following function:

     const date1 = "16/07/2022"
     const date2 = "07/16/2022"
    
      const dateToDateFormat = (date) => {
        const obj = date.split(/\//);
        return `${obj[1]}/${obj[0]}/${obj[2]}`;
      };
      
      console.log("New date1:", dateToDateFormat(date1))
      console.log("New date2:", dateToDateFormat(date2))

    B) STRING TO DATE

    Are you using your date results to simply render it as string in the frontend? In this case, the following part might be less relevant. However, in case of processing them by using a JS Date Object, you should be aware of the following. Unfortunately, you will not be able to convert all of your desired date results/formats, here in this case date strings "16/07/2022" & "07/16/2022", with native or common JS methods to JS Date Objects in an easy way due to my understanding. Check and run the following code snippet to see what I mean:

    const newDate1 = '07/16/2022'
    const newDate2 = '16/07/2022'
    
    const dateFormat1 = new Date(newDate1);
    const dateFormat2 = new Date(newDate2);
    
    console.log("dateFormat1", dateFormat1); 
    console.log("dateFormat2", dateFormat2);

    dateFormat2 with its leading 16 results in an 'invalid date'. You can receive more details about this topic in Mozilla's documentation. Furthermore, dateFormat1 can be converted to a valid date format but the result is not correct as the day is the 15th and not 16th. This is because JS works with arrays in this case and they are zero-based. This means that JavaScript starts counting from zero when it indexes an array (... without going into further details).

    CHECK VALIDITY

    In general, if you need to further process a date string, here "16/07/2022" or "07/16/2022", by converting it to a JS Date Object, you can in any case check if you succeed and a simple conversion with JS methods provides a valid Date format with the following function. At least you have kind of a control over the 'invalid date' problem:

    const newDate1 = '07/16/2022'
    const newDate2 = '16/07/2022'
    
    const dateFormat1 = new Date(newDate1);
    const dateFormat2 = new Date(newDate2);
    
    function isDateValidFormat(date) {
      return date instanceof Date && !isNaN(date);
    }
    
    console.log("JS Date Object?", isDateValidFormat(dateFormat1));
    console.log("JS Date Object?", isDateValidFormat(dateFormat2));

    Now, what is the benefit? You can use this function for further processing of your date format depending on what you need it for. As I said, it will not help us too much as we still can have valid date formats but with a falsy output (15th instead of 16th).

    CONVERT TO DATE OBJECT BY KNOWING THE FORMAT

    The following function converts any of your provided kinds of dates ("MM/DD/YYYY" or "DD/MM/YYYY") to a valid JS Date Object and - at the same time - a correct date. However, drawback is that it assumes to know what kind of input is used; "MM/DD/YYYY" or "DD/MM/YYYY". The dilemma is, that this information is crucial. For example, JS does not know if, for example, "07/12/2022" is "MM/DD/YYYY" or "DD/MM/YYYY". It would return a wrong result.

    const newDate1 = "07/16/2022"
    const newDate2 = "16/07/2022"
    
    function convertToValidDateObject(date, inputFormat) {
      const obj = date.split(/\//);
      const obj0 = Number(obj[0]) 
      const obj1 = Number(obj[1]) 
      const obj2 = obj[2]
      //
      // CHECK INPUT FORMAT
      if (inputFormat === "MM/DD/YYYY") {
        return new Date(obj2, obj0-1, obj1+1);
      } else if (inputFormat === "DD/MM/YYYY") {
        return new Date(obj2, obj1-1, obj0+1);
      } else {
        return "ERROR! Check, if your input is valid!"
      }
    
    }
    
    console.log("newDate1:", convertToValidDateObject(newDate1, "MM/DD/YYYY"))
    console.log("newDate2:", convertToValidDateObject(newDate2, "DD/MM/YYYY"))
    console.log("newDate2:", convertToValidDateObject(newDate2, "MM/YYYY"))

    If the wrong format is provided as a second argument, an error is provided in the console. In practise I suggest you to use a try-catch block ( I tried here, but it does not work here in this stackoverflow editor).

    I wish you good luck. Hope these information can help you.