|
Getting the last two digits of a year using getFullYear() (Javascript) |
|
|
Written by: Evan Cummings
Getting the last two digits of a year using getFullYear()Recently I have had to do some Javascript date manipulation and ran into the issue of formatting my results correctly. You aren't granted the diverse and flexible tools for working with dates in Javascript as you are in the .NET environment, however Javascript does expose alot of functionality for manipulating dates.
getYear()
My initial look into solving my problem naturally brought me to the GetYear() function, which was supposed to return the year in the two digit format that I needed. This posed a few problems:
1) It only returns two digit dates for dates between 1900 and 2000, which leads to the larger issue...
2)The whole Y2K doomsday scenario is illustrated by this function! Two digits by default is a bad idea, as one can see now.
The new and correct way to handle this involes using...
getFullYear()
This function completely eliminates the Y2K problem by returning 4-digit years. What if we need to have a 2 digit year? To accomplish this, we can utilize some of JavaScript's string manipulation functionality.
First, we need to grab an instance of a date:
var curDate = new Date();
Once we have this instance, we can extract a variety of information from it by invoking methods of the date object.
For our purpose, we want to grab ahold of the year:
var curYear = curDate.getFullYear();
Now that we have the year isolated, we can convert it to a string and manipulate it to the format we require by using the slice() function, which returns a part of the string based on a starting (and optional ending) index value. In our case we want our index to be 2 so we return the correct string.
curYear = curYear.toString().slice(2);
At this point, we have our current year in the 2 digit format we required. We can now do what we need to do with this, such as assign its value to a control or write it out to the screen:
document.write(curYear)
Content - JavaScript, Date Manipulation, ASP.NET |
|
|
|
|
|