# Displaying the date in MM/DD/YY format

Posted on

Problem

I spent about an hour and a half attempting to complete a problem from W3Resource. Here is what I came up with, which works. How can I shorten it?

function dateGet(){
var newDate = new Date();
var newMonth = newDate.getMonth() + 1;
var newDay = newDate.getDate();
var newYear = newDate.getFullYear();
var twoYear = (""+newYear).split("");
var combinedYear = twoYear[2] + twoYear[3];
var fullDate = 0;

if (newMonth < 10){
fullDate += 0 + newMonth + '/';
} else {
fullDate += newMonth + '/';
}

if (newDay < 10){
fullDate += 0 + newDay + '/';
} else {
fullDate += newDay + '/';
}

if (combinedYear < 10){
fullDate += 0 + combinedYear;
} else {
fullDate += combinedYear;
}

console.log(fullDate);

}

Solution

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.

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(). Looking at the case where the beginIndex is less than 0, .slice(-n) returns the last n characters from the string. For example "07".slice(-2) returns “07” and "027".slice(-2) returns “27”. For the month, we have to add a numerical 1 because javascript months are 0 based (that is, January is 0 and February is 1).

<script>
var newDate = new Date(); // get today's date
// add one to the month then prepend a "0" (note the quotes to make it a string), then we will slice off the last 2 characters for the month
// repeat for the day and year, although no need to add one to either of these
// also note that prepending the "0" to the year is not necessary, it is personal preference to remain consistent and to insure that it is a string and not a number
var fullDate = ("0"+(newDate.getMonth()+1)).slice(-2)
+ "/" + ("0" + newDate.getDate()).slice(-2)
+ "/" + ("0" + newDate.getFullYear()).slice(-2);

console.log(fullDate);
</script>

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"

)