ArticleZip > Javascript Date Getyear Returns 111 In 2011 Duplicate

Javascript Date Getyear Returns 111 In 2011 Duplicate

If you've ever encountered the perplexing situation where the `getYear()` function in JavaScript strangely returns `111` when you're expecting `2011`, you're not alone. This quirky behavior can throw anyone off, but fear not – we'll dive into the reasons behind this oddity and, more importantly, how to address it.

JavaScript's `getYear()` method, which is part of the `Date` object, returns the year minus 1900. This seemingly odd behavior can cause confusion if you're not aware of how this method operates under the hood. So, when you call `getYear()` in the year 2011, you'll get `111` as a result because `2011 - 1900 = 111`.

To ensure you get the expected result when working with dates, the recommended approach is to use the `getFullYear()` method instead of `getYear()`. The `getFullYear()` method returns the full 4-digit year, avoiding any confusion caused by the subtraction of 1900.

So, when you're dealing with date functionality in JavaScript and need to retrieve the year, remember to use `getFullYear()` to get the accurate and expected 4-digit year value. By making this simple switch in your code, you can prevent any headaches and ensure the correct year is always retrieved.

As an example, let's compare the use of `getYear()` and `getFullYear()` for the year 2011:

Javascript

const currentDate = new Date(2011, 0, 1); // January 1, 2011
console.log(currentDate.getYear()); // Output: 111
console.log(currentDate.getFullYear()); // Output: 2011

By using `getFullYear()`, you can clearly see that you get the desired `2011` instead of the potentially confusing `111` returned by `getYear()`.

In summary, JavaScript's `getYear()` method relies on a subtracted value that can lead to unexpected results, such as returning `111` for the year 2011. To avoid this confusion and ensure you receive the full year in 4-digit format, opt for using the `getFullYear()` method instead. By implementing this straightforward adjustment in your code, you can sidestep any discrepancies and handle date-related operations accurately and effectively.

×