Home  >  Article  >  Web Front-end  >  Is Setting Date.setFullYear(year, month, 0) a Reliable Way to Find the Last Day of a Month Across Browsers?

Is Setting Date.setFullYear(year, month, 0) a Reliable Way to Find the Last Day of a Month Across Browsers?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-05 08:44:02264browse

Is Setting Date.setFullYear(year, month, 0) a Reliable Way to Find the Last Day of a Month Across Browsers?

Finding the Last Day of a Month Accurately

It is known that setting the day value in Date.setFullYear to 0 retrieves the last day of the previous month. For example:

<code class="js">d = new Date();
d.setFullYear(2008, 11, 0); // Returns Sun Nov 30 2008</code>

This behavior is documented on Mozilla's website. However, it raises the question of whether this cross-browser feature is reliable or if alternative methods should be considered.

Cross-Browser Compatibility

Unfortunately, this feature is not cross-browser compatible. While it works in most major browsers, including Chrome, Firefox, and Safari, it does not behave consistently in Internet Explorer. In Internet Explorer, setting the day value to 0 may not always return the last day of the previous month.

Alternative Methods

To ensure accuracy across multiple browsers, alternative methods for finding the last day of a month are recommended. One reliable approach is to use the Date.getMonth() method, which returns the month number (0-based). You can then subtract one from this value to obtain the previous month's number and set the date to the last day of that month:

<code class="js">var month = 0; // January
var d = new Date(2008, month + 1, 0);
console.log(d.toString()); // Last day in January</code>

This method accurately retrieves the last day of a month, regardless of the browser being used.

The above is the detailed content of Is Setting Date.setFullYear(year, month, 0) a Reliable Way to Find the Last Day of a Month Across Browsers?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn