Search code examples
javascriptmomentjsdate-fns

How to format date to mm/dd/yyyy in moment / date-fns?


Here I am receiving the last updated data as an API response like this

let data = {
          "year": 2021,
          "monthValue": 11,
          "dayOfMonth": 9
         }

I have to covert this above object into this format MM/DD/YYYY.

Can convert the above data using string interpolation like this ${data.dayOfMonth}/${data.monthValue}/${data.year} But is there any other way we can use libraries to get this work done.

For e.g in the above string interpolation method, can't able to add 0 at the beginning of the dayOfMonth and monthValue when they are given as single digits.

can we achieve this using moment or date-fns?


Solution

  • You don't need a library just to zero-pad a 1–2 digit number:

    function pad2 (n) {
      return String(n).padStart(2, '0');
    }
    
    function format (data) {
      return `${pad2(data.monthValue)}/${pad2(data.dayOfMonth)}/${data.year}`;
    }
    
    
    const data = {
      "year": 2021,
      "monthValue": 11,
      "dayOfMonth": 9,
    };
    
    const result = format(data);
    console.log(result); // 11/09/2021