javascriptjsonstringifydataformat

How to JSON stringify a javascript New Date


I'm getting data from the form's json when the user fills out the calendar

const data= JSON.stringify(orderForm.informationDate)); 

Currently, I get data from JSON to print PDF in any way:

{"year":2023,"month":12,"day":22}

How to change data to DD.MM.YYYY format?


Solution

  • It is recommended to not store the date in dd.mm.yyyy format but if you insist

    const orderForm = { informationDate: {"year": 2023, "month": 12, "day": 22} };
    
    const ddmmyyyy = Object.values(orderForm.informationDate)
      .reverse()
      .map(val => String(val).padStart(2, '0'))
      .join('.');
    
    console.log(ddmmyyyy); // Outputs: 22.12.2023
    
    
    // With a replacer function
    
    
    const replacer = (key, value) => {
      if (key === 'informationDate')
        return Object.values(value)
          .reverse()
          .map(val => String(val).padStart(2, '0'))
          .join('.');
      return value;
    }
    
    const jsonString = JSON.stringify({ orderForm }, replacer, 2);
    console.log(jsonString);