How to JSON stringify a javascript New Date

112 Views Asked by At

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?

4

There are 4 best solutions below

4
mplungjan On BEST ANSWER

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);

1
Oswaldo Oliveira On

you can get the attributes of this object (data.year, data.month, data.day) and concatenate into a string

${data.day}.${data.month}.${data.year}

2
Christian On

Your question is based on a few misunderstandings:

  1. Dates cannot be serialized to/from json - there is no date/time data type.

  2. When you provide a date to the json serializer, you are providing an object, hence the serializer generates an object representation, like you saw:

    const myFakeDate = { year: 2023, month: 12, day: 22 };
    console.log(JSON.stringify(myFakeDate)); // => {"year":2023,"month":12,"day":22}
    
  3. The format that you mention in your question is clearly a string, since dates are typically stored internally as a number, not a string

  4. In your case, you have two options:

    1. convert the date/time object to a string before calling JSON.stringify:
      const data= {
         name: "John Doe",
         birthDate: {year: 1982, month: 3, day: 4}
      };
      
      data.birthDate = data.birthDate.day + '.' + data.birthDate.month + '.' + data.birthDate.year;
      
      console.log(JSON.stringify(data));
      
    2. Or use the "replacer" functionality:
      const data= {
         name: "John Doe",
         birthDate: {year: 1982, month: 3, day: 4}
      };
      
      const replacer = function(item) {
         if (item.year && item.month && item.day) {
           return item.day + '.' + item.month + '.' + item.year;
         }
      
         return item;
      };
      
      console.log(JSON.stringify(data, replacer));
      
  5. Keep in mind that you would/might need to reverse the process on the other side (e.g. to convert the string back to a date)

  6. If you are using Datetime objects (and not a plain object), you can check the object class instead of the existence of day/month/year properties. This depends on your exact code.

0
Ahmed Aziz ABBASSI On
  1. Use the power of destructuring.
  2. The format function role is to make sure days and months like 2 becomes 02.

const date = {year: 2023, month: 12, day: 22};
const { year, month, day } = date;
const format = (str) => String(str).padStart('0', 2);
const formattedDate = `${format(day)}.${format(month)}.${year}`;
const jsonData = JSON.stringify(formattedDate);
console.log(formattedDate);
console.log(jsonData);