The code looks good and works well. Since it provides a useful bit of work, you should convert it into a function. Then you can copy that function to another program if you need so.
function yyyymmdd() {
var x = new Date();
var y = x.getFullYear().toString();
var m = (x.getMonth() + 1).toString();
var d = x.getDate().toString();
(d.length == 1) && (d = '0' + d);
(m.length == 1) && (m = '0' + m);
var yyyymmdd = y + m + d;
return yyyymmdd;
}
To make this code a little easier to read, you should rename x
to now
.
You could also omit the calls to toString()
, which makes the code a little shorter. Plus, you should introduce the variables mm
and dd
, so that you don't reassign to the d
and m
variables. This is a generally useful pattern, because when stepping through the code you can always look at the variable definition to see how it was computed. This is not possible for variables that change their value during execution.
The modified code looks like this:
function yyyymmdd() {
var now = new Date();
var y = now.getFullYear();
var m = now.getMonth() + 1;
var d = now.getDate();
var mm = m < 10 ? '0' + m : m;
var dd = d < 10 ? '0' + d : d;
return '' + y + mm + dd;
}
Or, you could inline the last few lines:
function yyyymmdd() {
var now = new Date();
var y = now.getFullYear();
var m = now.getMonth() + 1;
var d = now.getDate();
return '' + y + (m < 10 ? '0' : '') + m + (d < 10 ? '0' : '') + d;
}
That last variant is harder to read though, therefore I prefer the previous one.
Another possibility is to define a helper function that produces a two-digit string:
function yyyymmdd() {
function twoDigit(n) { return (n < 10 ? '0' : '') + n; }
var now = new Date();
return '' + now.getFullYear() + twoDigit(now.getMonth() + 1) + twoDigit(now.getDate());
}
const components = [d.getFullYear(), d.getMonth() + 1, d.getDay()]; const paddings = [4, 2, 2]; components.map((component, i) => component.toString().padStart(paddings[i], '0')).join('');
\$\endgroup\$