HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

Finding the date 18 years ago

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thefindingdateyearsago

Problem

Here's what I have:

require('../../src/utils/date-object-to-yyyymmdd');
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.

Solution

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).

Code Snippets

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

Context

StackExchange Code Review Q#121084, answer score: 10

Revisions (0)

No revisions yet.