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

时间:2015-05-18 22:12:02

标签: 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

我怎样才能把它分开,这样我就可以摆脱一周的这一天,将2015年5月18日18:35:27分成4个不同的值? (2015年5月18日18:35:27)?

我以前做过这件事并且不确定为什么这次它会按角色分裂。

谢谢!

1 个答案:

答案 0 :(得分:7)

您将formattedDateSplit设置为整个日期字符串,unsplit:

var formattedDateSplit = formattedDate.toString();

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

formattedSplit.split(" ");

因为这是错误的变量名称;您可能的意思是:

formattedDateSplit = formattedDateSplit.split(" ");

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