Try,
alert((new Date()).getFullYear());
Answer from Sajeetharan on Stack OverflowCreate a new Date() object and call getFullYear():
new Date().getFullYear() // returns the current year
Example usage: a page footer that always shows the current year:
document.getElementById("year").innerHTML = new Date().getFullYear();
footer {
text-align: center;
font-family: sans-serif;
}
<footer>
<span id="year"></span> by Stack Overflow
</footer>
See also, the Date() constructor's full list of methods.
// Return today's date and time
var currentTime = new Date()
// returns the month (from 0 to 11)
var month = currentTime.getMonth() + 1
// returns the day of the month (from 1 to 31)
var day = currentTime.getDate()
// returns the year (four digits)
var year = currentTime.getFullYear()
// write output MM/dd/yyyy
document.write(month + "/" + day + "/" + year)
You can use Date():
this.curdate = (new Date().getMonth() + 1).toString() + '-' + new Date().getFullYear().toString();
Note that new Date().getMonth() start from 0 to 11 so you need to +1 to make it 1 to 12.
Update:
To add leading 0 based on related post you can do: '0' + (new Date().getMonth() + 1).toString().slice(-2)
Explanation:
Since '0' is not a number but a string when you add (+) with another string then it would be concatenated. Then .slice(-2) gives us the last two characters of the string. If it's single digit then it would be 0xmonth, if it's double digits then it would be 0 + xx month which are returned.
See snippet for example:
var d = '0' + (new Date().getMonth() + 1).toString().slice(-2) + '-' + new Date().getFullYear().toString();
document.getElementById("demo").innerHTML = d;
<p id="demo"></p>
Alternatively if you don't want a trailing 0 on double digit months (Oct, Nov, Dec) you could do a little checking based on month digit length: (new Date().getMonth() + 1).length > 1 ? new Date().getMonth() + 1 : '0' + (new Date().getMonth() + 1)
var month = (new Date().getMonth() + 1).length > 1 ? new Date().getMonth() + 1 : '0' + (new Date().getMonth() + 1);
var date = (month).toString().slice(-2) + '-' + new Date().getFullYear().toString();
document.getElementById("demo").innerHTML = date;
<p id="demo"></p>
You can use the built-in date pipe:
{{date | date:'MM-dd'}}
and pass your own format.
Update
Try something like for a JS-only solution:
m = new Date().getMonth().toString() + 1;
y = new Date().getFullYear().toString();
return m + '-' + y;