Reputation: 8502
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.
Upvotes: 3
Views: 301
Reputation: 17898
You can also try,
var date = new Date(optionalDate || Date.now());
date
gives you the current date IF optionalDate
is either '', null or false
.
Upvotes: 1
Reputation: 3698
If You pass null inside Date object it will return Thu Jan 01 1970
so you can't do that instead you can check if that exists like below:
optionalDate?new Date(optionalDate):new Date;
this will return a date object from optional date if possible otherwise today's date
Upvotes: 1
Reputation: 782785
Use a ternary expression:
var date = optionalDate ? new Date(optionalDate) : new Date();
Upvotes: 2