Javascript current date with an argument

- 1 answer

Ad

Pretty straightforward, I have this:

var optionalDate;
var date = new Date(optionalDate || null);

What I want to do is, create a date with the optional date if available, if not, create today's date. If I pass null to the function (as it is in the example), it will create Wed Dec 31 1969, If I pass "", won't work, and if I leave blank, also won't work..

Is there any parameter that can be used to get today's date (I know the absence of parameters would work, but wouldn't be valid in the || operation) . Sorry for the simple question, but I couldn't find the answer to this.

Ad

Answer

Ad

You can also try,

var date = new Date(optionalDate || Date.now());

date gives you the current date IFoptionalDate is either '', null or false.

Ad
source: stackoverflow.com
Ad