Avatar ·

How to properly format dates in JavaScript? (DD.MM.YYYY format and others)

Hi everyone! I just started learning JavaScript and encountered a problem with date formatting. I need to output the current date in the format "12.05.2023" (day.month.year), but the standard new Date() output gives something like "Fri May 12 2023 14:30:00 GMT+0300". This is completely unreadable for the user.\n\nI tried using getDate(), getMonth(), getFullYear() methods, but it turns out wrong:\n\n```javascript\nconst now = new Date();\nconsole.log(now.getDate() + '.' + now.getMonth() + '.' + now.getFullYear());\n// Outputs: 12.4.2023 (month is 4 for some reason, not 5!)\n```\n\nAnother problem: if the day or month is less than 10, there is no leading zero. It outputs "1.5.2023" instead of "01.05.2023".\n\nTell me how to format dates correctly and cleanly? Are there built-in methods or do I need to write my own function? And what to do