简体   繁体   中英

Splitting strings in JavaScript

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('/');

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]

try

dat.toString().split('/');

but this solution is locale dependent

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM