I tried to split data as below, but the error "dat.split is not a function" displays. Anyone know how can I solve this problem?
var dat = new Date("2009/12/12");
var r = dat.split('/');
Jeff Atwood
64.1k48 gold badges153 silver badges153 bronze badges
asked Apr 17, 2009 at 5:50
Jin Yong
44k72 gold badges145 silver badges197 bronze badges
-
@Jin Yong: Was there a special reason that made you delete your post? It's a valid question after all... (@Jeff Atwood: Thanks for undeleting.)Tomalak– Tomalak2009年04月17日 10:01:47 +00:00Commented Apr 17, 2009 at 10:01
3 Answers 3
You can't split() a Date - you can split() a String, though:
var dat = "2009/12/12";
var r = dat.split('/');
returns:
["2009", "12", "12"]
To do the equivalent with a date, use something like this:
var dat = new Date();
var r = [dat.getFullYear(), dat.getMonth() + 1, dat.getDate()];
returns:
[2009, 4, 17]
answered Apr 17, 2009 at 5:54
Tomalak
340k68 gold badges547 silver badges635 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Do you just want to get the year, month and day? In that case you'd be better off using a non-locale dependent solution and calling the following functions:
dat.getDay();
dat.getMonth();
dat.getFullYear();
Sure they won't be zero padded, but that's easy enough to do.
Jeff Atwood
64.1k48 gold badges153 silver badges153 bronze badges
Comments
try
dat.toString().split('/');
but this solution is locale dependent
Jeff Atwood
64.1k48 gold badges153 silver badges153 bronze badges
answered Apr 17, 2009 at 5:53
oscarkuo
10.4k6 gold badges51 silver badges62 bronze badges
2 Comments
Crescent Fresh
new Date("2009/12/12").toString().split('/'); // ["Sat Dec 12 2009 00:00:00 GMT-0500 (Eastern Standard Time)"]oscarkuo
hey did I just found a bug in stackoverflow, I am pretty sure I deleted my answer because I found there's a problem as noted by the comment above. Plus, the author of the comment above is 'null'.
lang-js