1
var str ="20110725";
var dd = str.substring(6);
var mm = str.substring(4,2);
var yyyy = str.substring(0,3);
alert(dd );//25
alert(mm);//11
alert(yyyy );//2011

Instead of the above output, I expected "25" as date, "07" as month and "2011" as year. Please correct me.

Noel Evans
  • 8,113
  • 8
  • 48
  • 58
Someone
  • 10,405
  • 23
  • 67
  • 100
  • So, now you have a new problem - you should probably accept an answer and create a new stackoverflow question fon the month[mon] business. I know the answer to that - but I don't want to muddy these waters. Thanks. – jimbo Jul 25 '11 at 23:07

4 Answers4

3

I think you want substr(), not substring(). They're different.

jimbo
  • 11,004
  • 6
  • 29
  • 46
  • not much difference. except it would be a little harder to read. – Joseph Marikle Jul 25 '11 at 22:13
  • @Joseph: they are far from the same; see here: http://stackoverflow.com/questions/3745515/what-is-the-difference-between-substr-and-substring – Reid Jul 25 '11 at 22:14
  • I know they are different... I didn't deny it... but they are similar: substr(startPosition,endPosition) substring(startPosition,length). I use these on a a daily basis. substr is harder to read in this case because instead of (4,2) for month (length of two chracters) it would be (4,6) (positions 4 and 6). that is harder to read imo and non-intuitive. – Joseph Marikle Jul 25 '11 at 22:17
  • But, in this case, the only one it's affecting is the "mm" calculation. – James Curran Jul 25 '11 at 22:18
  • I see.. I misread the posters comments... I thought those three numbers were the desired result :P – Joseph Marikle Jul 25 '11 at 22:19
  • Right, OP is complaining that (4,2) is going from position 4 to position 2 when he wants from position 4 forward 2 positions. He's using substring() as though it were substr(). I stand by my recommendation. :) – jimbo Jul 25 '11 at 22:54
2

You should have

var mm = str.substring(4, 6);
Paul Sonier
  • 38,903
  • 3
  • 77
  • 117
2

Instead of:

var mm = str.substring(4, 2)

Do:

var mm = str.substring(4, 6)
Jon Martin
  • 3,252
  • 5
  • 29
  • 45
1

Try this. You also need a 4, not a 3 for your year.

var str ="20110725";
var dd = str.substr(6);
var mm = str.substr(4,2);
var yyyy = str.substr(0,4);
alert(dd );//25
alert(mm);//11
alert(yyyy );//2011
JustBeingHelpful
  • 18,332
  • 38
  • 160
  • 245