Get the current year in JavaScript

Get the current year in JavaScript

How do I get the current year in JavaScript?


Solution 1:

Create a new Date() object and call getFullYear():

new Date().getFullYear()
// returns the current year

Hijacking the accepted answer to provide some basic example context like a footer that always shows the current year:

    &copy; <span id="year">2018</span>

Somewhere else executed after the HTML above has been loaded:

    document.getElementById("year").innerHTML = new Date().getFullYear();
document.getElementById("year").innerHTML = new Date().getFullYear();
footer {
  text-align: center;
  font-family: sans-serif;
    &copy; <span id="year">2018</span> by FooBar

Solution 2:

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

Solution 3:

Here is another method to get date

new Date().getDate()          // Get the day as a number (1-31)
new Date().getDay()           // Get the weekday as a number (0-6)
new Date().getFullYear()      // Get the four digit year (yyyy)
new Date().getHours()         // Get the hour (0-23)
new Date().getMilliseconds()  // Get the milliseconds (0-999)
new Date().getMinutes()       // Get the minutes (0-59)
new Date().getMonth()         // Get the month (0-11)
new Date().getSeconds()       // Get the seconds (0-59)
new Date().getTime()          // Get the time (milliseconds since January 1, 1970)

Solution 4:

for current year we can use getFullYear() from Date class however there are many function which you can use as per the requirements, some functions are as,

var now = new Date()
console.log("Current Time is: " + now);

// getFullYear function will give current year 
var currentYear = now.getFullYear()
console.log("Current year is: " + currentYear);

// getYear will give you the years after 1990 i.e currentYear-1990
var year = now.getYear()
console.log("Current year is: " + year);

// getMonth gives the month value but months starts from 0
// add 1 to get actual month value 
var month = now.getMonth() + 1
console.log("Current month is: " + month);

// getDate gives the date value
var day = now.getDate()
console.log("Today's day is: " + day);

Solution 5:

Such is how I have it embedded and outputted to my HTML web page:

<div class="container">
    <p class="text-center">Copyright &copy; 
            var CurrentYear = new Date().getFullYear()

Output to HTML page is as follows:

Copyright © 2018