create date object minus 18 years in typescript

To create a Date object minus 18 years in TypeScript, you can use the Date constructor to create a new date object with the current date and then subtract 18 years from it using the setFullYear() method.

index.ts
const today = new Date();
const eighteenYearsAgo = new Date(today.getFullYear() - 18, today.getMonth(), today.getDate());
122 chars
3 lines

In the above code, today is the current date object obtained through the Date constructor. We then create a new date object eighteenYearsAgo by subtracting 18 years from the current year using the getFullYear() method and passing it as the first argument to the Date constructor.

The second and third arguments for the Date constructor are the month and date respectively. In this example, we are using the values from the today object to preserve the month and date of the current date.

Alternatively, you could also use the setFullYear() method to subtract 18 years from an existing date object.

index.ts
const someDate = new Date('2000-01-01');
someDate.setFullYear(someDate.getFullYear() - 18);
92 chars
3 lines

In the above code, we create a new Date object someDate and set it to a specific date using the Date constructor. We then subtract 18 years from someDate using the setFullYear() method.

gistlibby LogSnag