Calling format('YYYY') will invoke moment's string formatting functions, which will parse the format string supplied, and build a new string containing the appropriate data. Since you only are passing YYYY , then the result will be a string containing the year. If all you need is the year, then use the year() function.
To get the current year, use the getFullYear() JavaScript method. JavaScript date getFullYear() method returns the year of the specified date according to local time. The value returned by getFullYear() is an absolute number.
function subtractYears(numOfYears, date = new Date()) { date. setFullYear(date. getFullYear() - numOfYears); return date; } // 👇️ subtract 1 year from current Date const result = subtractYears(1); // 👇️ Subtract 2 years from another Date const date = new Date('2022-04-26'); // 👇️ Sun Apr 26 2020 console.
This will create a Date
exactly one year in the future with just one line. First we get the fullYear
from a new Date
, increment it, set that as the year of a new Date
. You might think we'd be done there, but if we stopped it would return a timestamp, not a Date
object so we wrap the whole thing in a Date
constructor.
new Date(new Date().setFullYear(new Date().getFullYear() + 1))
You should use getFullYear()
instead of getYear()
. getYear()
returns the actual year minus 1900 (and so is fairly useless).
Thus a date marking exactly one year from the present moment would be:
var oneYearFromNow = new Date();
oneYearFromNow.setFullYear(oneYearFromNow.getFullYear() + 1);
Note that the date will be adjusted if you do that on February 29.
Similarly, you can get a date that's a month from now via getMonth()
and setMonth()
. You don't have to worry about "rolling over" from the current year into the next year if you do it in December; the date will be adjusted automatically. Same goes for day-of-month via getDate()
and setDate()
.
As setYear()
is deprecated, correct variant is:
// plus 1 year
new Date().setFullYear(new Date().getFullYear() + 1)
// plus 1 month
new Date().setMonth(new Date().getMonth() + 1)
// plus 1 day
new Date().setDate(new Date().getDate() + 1)
All examples return Unix timestamp, if you want to get Date
object - just wrap it with another new Date(...)
Use this:
var startDate = new Date();
startDate.setFullYear(startDate.getFullYear() - 1);
Using some of the answers on this page and here, I came up with my own answer as none of these answers fully solved it for me.
Here is crux of it
var startDate = "27 Apr 2017";
var numOfYears = 1;
var expireDate = new Date(startDate);
expireDate.setFullYear(expireDate.getFullYear() + numOfYears);
expireDate.setDate(expireDate.getDate() -1);
And here a a JSFiddle that has a working example: https://jsfiddle.net/wavesailor/g9a6qqq5/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With