0

I'm trying to get the date in the above format, and I'm doing it in Javascript. Here is what I'm trying to do, but it doesn't seem to want to work. It's giving me an object doesn't support this property or method error.

var today = new Date();
var currentDate = ('0' + today.getDate()).slice(-2) + '-' + ('0' + (today.getMonth()+1)).slice(-2) + '-' + today.getFullYear().slice(-2);
alert(currentDate);

The idea, if it isn't obvious, is to add a 0 to the front of each piece and then slice off the last two digits. That way, if it's a 9, it'll add a 0 to the front, and keep the 09. If it's a 10, it'll add a 0 (so we have 010) but only keep the last two digits: 10.

However, I've got that awesome error, so I can't figure out what I'm doing wrong.

Alex Kibler
  • 4,674
  • 9
  • 44
  • 74
  • 1
    I think this might help answer your question http://stackoverflow.com/questions/1056728/formatting-a-date-in-javascript – Matt.C Jul 02 '13 at 16:21
  • 1
    Did you read the following thread: http://stackoverflow.com/questions/1056728/formatting-a-date-in-javascript?rq=1? – Matthias Holdorf Jul 02 '13 at 16:23

1 Answers1

3
today.getFullYear().slice(-2)

is your problem. .getFullYear will return a number, and those have no slice method. Just convert it to a string before:

(''+today.getFullYear())
// or
today.getFullYear().toString()
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Ohhhh, yep, that's it. I just needed to put a `'0' +` in front of it to get it to be a string. Thanks! I'm used to C++ where you manually set the type of a variable, haha – Alex Kibler Jul 02 '13 at 16:23