日期转换难题

时间:2014-10-31 22:10:18

标签: javascript

在将日期转换为字符串和字符串到日期时,在javascript中获得一些不一致的结果。正如评论中所述,这段代码似乎很奇怪:

// Start with a string literal        
var s1 = "10/31/2014";

// Convert string to date
var f1 = s1.split("/");
var d1 = new Date(f1[2], (f1[0] - 1), f1[1]);
alert("Date from string: " + d1); // works

// Convert that date to a string
a1 = (d1.toLocaleString("en-US")).split(" ", 1);
alert("Array[0] from split: " + a1[0]); // works
s2 = a1[0];
alert("String from Array[0] assignment: " + s2);

// Convert string to date (identical to before)
var f2 = s2.split("/");
var d2 = new Date(f2[2], (f2[0] - 1), f2[1]);
alert("Date from String: " + d2); // fails: "Invalid date"

任何人都知道为什么这个字符串不是字符串?

顺便说一下,改变

s2 = a1[0];

s2 = a1[0].toString();

相当可预测地改变什么。想法?

http://jsfiddle.net/pfvh6fed/1/

2 个答案:

答案 0 :(得分:1)

如果您打印console.log(f2[2]);,您会注意到您实际上正在使用附带的逗号捕获2014,。删除它,它应该正常工作。

编辑:然而,做你正在尝试的事情的最佳方式应该是语义方式:

day = date.getDay() 

month = date.getMonth() 

year = date.getFullYear()

答案 1 :(得分:0)

您的年份字符串末尾有一个逗号,添加.replace(',','')修复了问题

// Start with a string literal        
var s1 = "10/31/2014";

// Convert string to date
var f1 = s1.split("/");
var d1 = new Date(f1[2], (f1[0] - 1), f1[1]);
alert("Date from string: " + d1); // works

// Convert that date to a string
a1 = (d1.toLocaleString("en-US")).split(" ", 1);
alert("Array[0] from split: " + a1[0]); // works
s2 = a1[0];
alert("String from Array[0] assignment: " + s2);

// Convert string to date (identical to before)
var f2 = s2.split("/");
var d2 = new Date(f2[2].replace(",",""), (f2[0] - 1), f2[1]);
alert("Date from String: " + d2); // ?