Y2K and Your Scriptsby George Chiang of Website AbstractionHome/JavaScript/Guest- Y2K A recent survey revealed that over 50% of people secretly hoped for a small disaster to occur on Millennium day (hmmmm). Well, to the disappointment of billions, then, Y2K came without a hitch, and life went on as usual- for the most part, that is. Around the world, minor glitches were reported, and among them, a JavaScript-related one. Apparently, a good number of Netscape browsers contain a Y2K bug that causes dates rendered by JavaScript to be displayed incorrectly after the cross over. The bug also plagues Internet Explorer, though only in older versions (IE 2). Here's the problem. Date.getYear(), JavaScript's method to retrieve the year, is defective in certain browsers, and resets to "100" on year 2000. Calling it now (year 2000) returns 100", year 2001 returns "101", and so on. This problematic behavior with Date.getYear() is manifested in the following browsers:
NS 2 Other versions not mentioned generally are Y2K okay (NS 3, NS 4.0 thru NS 4.05, IE 4+). Done with the problem, now onto the solution. To have JavaScript accurately write out the correct year starting in Y2K, simply conditionally add 1900 to Date.getYear(). The condition to test for is whether the year is less than 1000. So, with that in mind, here's the fixed code:
var year=mydate.getYear() file://Y2K bug fix if (year < 1000) year+=1900 Variable "year" will now always contain the correct 4 digit year, regardless of which browser runs it. Check the source of some of our Date scripts (http://wsabstract.com/script/cutindex1.shtml), and you'll notice the above snippet in most of them. Now you know why they're there, and how to go about fixing your OWN Y2K incompatible scripts!
This tutorial is written and contributed to Pageresource.com by George Chiang. He mantains Website Abstraction (http://wsabstract.com), a site dedicated to JavaScript programming and script help. Other Topics: ASP/PHP | DHTML | Java The tutorials and articles on these pages are © 1997-2010 by John Pollock and may not be reposted without written permission from the author, and may not be reprinted for profit. Disclaimer. |