Whenever you find yourself writing code that feels the same, consider whether you can create a function to do it. For example consider using a function for padding to two digits.


Instead of turning newYear into a string so you can split it on digits, consider using the remainder operator (%). That is, var newYear = newDate.getFullYear() % 100;

Although (actually, because) javascript lets you play fast and loose with whether a variable is a string or a number or something else, it's worth avoiding switching between them where possible. It also has the slight advantage that it always gets the last two digits, even if the year had 3 or 5 digits in it. (Of course that won't be relevant for a very long time if it only prints the current date, but you shouldn't bank on that.)


I would be inclined to make this code slightly more general by allowing it to return rather than print out the formatted string, and allowing it to take a Date as a parameter rather than only using the current date. If you do want to print it, you can always do that with the output.

Of course that might actually be marginally longer, but I think that's worth it. Unless you're in a smallest number of characters competition, it is better to have readable, flexible code than short code if they conflict. Length is only a problem when there's too much there to keep in your head how it fits together.


Sticking strings together one bit at a time with + is an expensive thing to do. It's worth getting into the habit of using something like join As shown in jstudenski's code.

Answer from Josiah on Stack Exchange
🌐
Squash
squash.io › how-to-format-javascript-date-as-yyyy-mm-dd
How to Format JavaScript Dates as YYYY-MM-DD
Then, we use the toISOString() method to get the ISO format string representation of the date. We split the string at the 'T' character to extract the date part. Finally, we replace the '-' characters with spaces using the replace() method to get the desired YYYY MM DD format. Related Article: How to Use Async Await with a Foreach Loop in JavaScript
Discussions

javascript - Displaying the date in MM/DD/YY format - Code Review Stack Exchange
You are wanting to shorten your code. Your code is meant to format the current date as MM/DD/YY. This can be accomplished by treating it the parts as strings appended to a "0" incase they are less than 10 so 7 becomes "07" and 27 becomes "027". Once this is done, you can use the String.slice(). More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
July 25, 2018
Format JavaScript date as yyyy-mm-dd - Stack Overflow
As mikeypie pointed out in the comments, if the date string is already in the expected output format and the local timezone is west of UTC, then new Date('2022-05-18') results in 2022-05-17. And a user's locale (eg. MM/DD/YYYY vs DD-MM-YYYY) may also impact how a date is parsed by new Date(...). More on stackoverflow.com
🌐 stackoverflow.com
html - How to get current formatted date dd/mm/yyyy in Javascript and append it to an input - Stack Overflow
I would like to add a current date to a hidden HTML tag so that it can be sent to the server: How can I add a More on stackoverflow.com
🌐 stackoverflow.com
Format a JavaScript Date to YYYY MM DD - Mastering JS
As wild as it seems that this would need to be in a course called "Mastering JS"... I definitely have to look it up every time I need to format a date. More on reddit.com
🌐 r/learnjavascript
2
3
August 3, 2021
🌐
PHP
php.net › manual › en › datetime.format.php
PHP: DateTimeInterface::format - Manual
The format of the outputted date string. See the formatting options below.
Top answer
1 of 3
5

Whenever you find yourself writing code that feels the same, consider whether you can create a function to do it. For example consider using a function for padding to two digits.


Instead of turning newYear into a string so you can split it on digits, consider using the remainder operator (%). That is, var newYear = newDate.getFullYear() % 100;

Although (actually, because) javascript lets you play fast and loose with whether a variable is a string or a number or something else, it's worth avoiding switching between them where possible. It also has the slight advantage that it always gets the last two digits, even if the year had 3 or 5 digits in it. (Of course that won't be relevant for a very long time if it only prints the current date, but you shouldn't bank on that.)


I would be inclined to make this code slightly more general by allowing it to return rather than print out the formatted string, and allowing it to take a Date as a parameter rather than only using the current date. If you do want to print it, you can always do that with the output.

Of course that might actually be marginally longer, but I think that's worth it. Unless you're in a smallest number of characters competition, it is better to have readable, flexible code than short code if they conflict. Length is only a problem when there's too much there to keep in your head how it fits together.


Sticking strings together one bit at a time with + is an expensive thing to do. It's worth getting into the habit of using something like join As shown in jstudenski's code.

2 of 3
4

Your current function do a lot of unnecessary manipulations: picking month, day and year from the Date object, coverting from number to string and back, splitting, concatenating, updating on several conditions... IMHO, it's too long and unefficient.

So I'd suggest you shorten it using toLocaleDateString method of Date object prototype (see comments in the code):

console.log(
  (new Date()) // take a new Date object.
               // BTW, you can take another time just by 
               // passing any valid time string as a parameter
               // e.g. new Date('7/8/2008')

    .toLocaleDateString('en-US', {year:'2-digit', month:'2-digit', day:'2-digit'})
     // take a locale string from the Date object 
     // passing locale 'en-US' and formatting options as parameters
     // So this returns you a string like "07/08/08"
                             

)

🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Intl › DateTimeFormat
Intl.DateTimeFormat - JavaScript | MDN
The initial value of the [Symbol.toStringTag] property is the string "Intl.DateTimeFormat". This property is used in Object.prototype.toString(). ... Getter function that formats a date according to the locale and formatting options of this DateTimeFormat object.
Find elsewhere
🌐
Reddit
reddit.com › r/learnjavascript › format a javascript date to yyyy mm dd - mastering js
r/learnjavascript on Reddit: Format a JavaScript Date to YYYY MM DD - Mastering JS
August 3, 2021 - This subreddit is for anyone who wants to learn JavaScript or help others do so. Questions and posts about frontend development in general are welcome, as are all posts pertaining to JavaScript on the backend. Members · upvotes · · comments · How the C# convert yyyy-mm-dd+hh:ss into 01:00?
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Date
Date - JavaScript | MDN
The format is as follows: ... YYYY is the year, with four digits (0000 to 9999), or as an expanded year of + or - followed by six digits. The sign is required for expanded years. -000000 is explicitly disallowed as a valid year. MM is the month, with two digits (01 to 12).
🌐
W3Schools
w3schools.com › js › js_date_formats.asp
JavaScript Date Formats
Independent of input format, JavaScript will (by default) output dates in full text string format: ISO 8601 is the international standard for the representation of dates and times. The ISO 8601 syntax (YYYY-MM-DD) is also the preferred JavaScript date format:
🌐
MUI X
mui.com › x › react-date-pickers › date-picker
React Date Picker component - MUI X
You can show a helper text with the date format accepted: Helper text example · MM/DD/YYYY · Helper text example · MM/DD/YYYY · <DatePicker label="Helper text example" slotProps={{ textField: { helperText: 'MM/DD/YYYY', }, }} /> Press Enter to start editing ·
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-format-javascript-date-as-yyyy-mm-dd
How To Format JavaScript Date as yyyy-mm-dd? - GeeksforGeeks
June 24, 2025 - We use JavaScript built-in help methods from the Date class that help us to create a formatted version of the current date in the form of yyyy-mm-dd.
🌐
Sabe
sabe.io › blog › javascript-format-date-yyyy-mm-dd
How to Format a Date to YYYY MM DD in JavaScript | Sabe
May 26, 2022 - JAVASCRIPTconst date = new Date(); const dateParts = date.toISOString().split("T"); const formatted = dateParts[0].replace(/-/g, ''); console.log(formatted); ... In this post, we looked at the easiest way to format a Date into the YYYY-MM-DD ...
🌐
Medium
ckramp.medium.com › converting-iso-8601-date-format-to-javascript-mm-dd-yyyy-date-format-cab0dda9c9b7
Converting ISO-8601 date format to JavaScript MM/DD/YYYY date format - Christian Kramp - Medium
November 26, 2022 - var isodate = new Date("2021-12-31T00:00:00.000Z"); var localedateformat = isodate.toLocaleDateString('en-US'); What you’ll get is the following format: mm/dd/yyyy. This is the format for the US.
🌐
Moment.js
momentjs.com
Moment.js | Home
moment().format('MMMM Do YYYY, h:mm:ss a'); moment().format('dddd'); moment().format("MMM Do YY"); moment().format('YYYY [escaped] YYYY'); moment().format();
🌐
Vishalgarg
vishalgarg.io › articles › how-to-format-a-date-in-javascript
How to Format a Date in JavaScript, Date Formatting in JS - Vishal Garg
April 4, 2025 - Intl.DateTimeFormat : The Intl.DateTimeFormat object is a built-in object in JavaScript that allows you to format dates and times according to the locale and options you specify. It provides a more flexible way to format dates compared to string concatenation. For example, to format a date as "DD/MM/YYYY" using Intl.DateTimeFormat, you can do the following: