将其转换为字符串后吐出日期

SS1*_*113 4 javascript

我有一个以毫秒为单位的日期,我将其转换为可读日期.然后我将它转换成一个字符串,这样我就可以拆分它并将其分解以使用我需要的部分.问题是当我按空间分解它时,它会自动分解每个字符,并且不会在有空格的地方将其拆分.谁能解释为什么以及我做错了什么?

这是我的代码:

var formattedDate = new Date(somedateMS);

var formattedDateSplit = formattedDate.toString();

formattedDateSplit.split(" ");

console.log(formattedDateSplit);  // Mon May 18 2015 18:35:27 GMT-0400 (Eastern Daylight Time)
console.log(formattedDateSplit[0]); // M
console.log(formattedDateSplit[1]); // o
console.log(formattedDateSplit[2]); // n
console.log(formattedDateSplit[3]); // [space]
console.log(formattedDateSplit[4]); // M
console.log(formattedDateSplit[5]); // a
console.log(formattedDateSplit[6]); // y
Run Code Online (Sandbox Code Playgroud)

我怎么能把它分开以便我可以摆脱一周中的哪一天,并将2015年5月18日18:35:27分成4个单独的值?(2015年5月18日18:35:27)?

我以前做过这个,不知道为什么这次它会被角色分裂.

谢谢!

Poi*_*nty 7

您正在设置formattedDateSplit整个日期字符串,unsplit:

var formattedDateSplit = formattedDate.toString();
Run Code Online (Sandbox Code Playgroud)

然后你这样做,这可能是一个错字:

formattedSplit.split(" ");
Run Code Online (Sandbox Code Playgroud)

因为这是错误的变量名称; 你可能意味着什么:

formattedDateSplit = formattedDateSplit.split(" ");
Run Code Online (Sandbox Code Playgroud)

您将获得单个字符,因为后续代码只是索引到字符串本身,而不是字符串的拆分版本.该.split()函数返回数组,因此您必须将其分配给某个东西; 它不会修改字符串.