Here's what I have:

var eighteenYearsAgo = new Date();
eighteenYearsAgo.setTime(eighteenYearsAgo.valueOf() - 18 * 365 * 24 * 60 * 60 * 1000);
eighteenYearsAgo = eighteenYearsAgo.yyyymmdd();

Basically, I am generate a date, setting it to 18 years ago (from today), and then converting it to yyyy-mm-dd format via an external function. I feel like this is quite verbose as is, but can't quite wrap my head around how to do it in a shorter way.

  • 2
    \$\begingroup\$ You do realize that you haven't taken leap years into consideration, right? \$\endgroup\$ – BCdotWEB Feb 25 '16 at 14:41

Why don't you use the setFullYear() method?

eighteenYearsAgo = eighteenYearsAgo.setFullYear(eighteenYearsAgo.getFullYear()-18);

Instead of using the yyymmdd() function, you can also use the Date.toISOString() method. This will also show the time... but you can get rid of it in several ways (split on "T" or use a regular expression).

  • \$\begingroup\$ Okay sure, good point, but doesn't make the code much terser. \$\endgroup\$ – j_d Feb 25 '16 at 15:14
  • 1
    \$\begingroup\$ That's true. But it takes leap years in consideration. \$\endgroup\$ – Berend Feb 25 '16 at 15:27
  • \$\begingroup\$ Ah, very good point. And by the way, my yyyymmdd function is essentially doing what you're saying, toISOString and splitting. Cheers. \$\endgroup\$ – j_d Feb 25 '16 at 15:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.