PDA

View Full Version : Two digits for year in javascript



Dimi Cost
04-06-2011, 05:15 PM
Hello,I have problem because I cannot find the solution with 2 digits for year in javascript. I use this:
var result = today.getFullYear().substring(2, 4);
I would like help.

jscheuer1
04-06-2011, 05:29 PM
The getFullYear() method returns a number. The substring() method can only be applied to a string. The getFullYear value needs to be type converted to a string before using a string method on it, so:


var result = today.getFullYear().toString(10).substring(2, 4);

Or (probably more efficient):


var result = (today.getFullYear() + '').substring(2, 4);

Note: In the second example '' is an empty string delimited by single quotes ('). There's nothing inside, not even a space. If in doubt, copy and paste it.