[Solved-5 Solutions] Get the current year in javascript - javascript tutorial



Problem:

How to get the current year in JavaScript ?

Solution 1:

To get the current year, we can use the getFullYear() method. This method returns the current year and like the getDate and getMonth, it does not expect any argument.

Example:

var t1 = new Date();
var year = t1.getFullYear(); 
console.log(year); 

Solution 2:

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

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

Solution 3:

// 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 4:

Here is another method to get the 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 5:

To simplify all time related operations, we can use a libary such as moment js.

moment().year();

Or in UTC time :

moment().utc().year();


Related Searches to Get the current year in javascript - javascript tutorial