1

I have the following snippet of JavaScript code I use for rendering a date range from the current month to the same month last year:

var today = new Date();
var endDate = new Date(today.getFullYear(), today.getMonth(), 1);
var startDate = new Date(endDate.getYear() - 1, endDate.getMonth() - 1, 1);

In IE 8 it gives me the correct date range:

Fri Jun 1 00:00:00 MST 2012 - Mon Jul 1 00:00:00 MST 2013

When I run the same code in Chrome, I get the following date range:

Wed Jun 01 0112 00:00:00 MST - Mon Jul 01 2013 00:00:00 MST

The year for the start date is 0112. What do I need to do in order to get the correct date range in IE and Chrome?

1
  • "The getYear method returns the year minus 1900" - see MDN Commented Jul 22, 2013 at 19:42

2 Answers 2

5

What do I need to do in order to get the correct date range in IE and Chrome?

Use getFullYear() for both endDate and startDate:

var startDate = new Date(endDate.getFullYear() - 1, endDate.getMonth() - 1, 1);

getYear() was intended to return the short year -- 96 for 1996. But, its behavior varied between browsers for dates with years outside the 1900s.

Specifically, IE 4 - 8 imitate getFullYear() for other years:

In Internet Explorer 4.0 through Internet Explorer 8 standards mode, the formula depends on the year. For the years 1900 through 1999, the value returned is a 2-digit value that is the stored year minus 1900. For dates outside that range, the 4-digit year is returned. For example, 1996 is returned as 96, but 1825 and 2025 are returned as is.

IE9 returned to the standardized behavior that you're witnessing in Chrome where (pseudo-code):

getYear() == getFullYear() - 1900
1
  • Thanks for the detailed explanation with answer. Commented Jul 22, 2013 at 19:50
2

getYear is a deprecated function that returns the year minus 1900. You should use getFullYear() instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.