我遇到了一个非常奇怪的问题。
我有两个Javascript字符串变量,它们从两个文本框中获取数据。
从表格单元格中拉出第三个字符串。但是,当它转换为Javascript Date()时,其日期会发生变化。我不知道为什么会这样。
我将通过代码发表评论,以帮助解释发生了什么。
//get the text from the first textbox (from date)
var valueFrom = document.getElementById('selected-submittedDate-from').value;
//convert the string into the right format
var formatDateString = function (unformatted) {
var parts = unformatted.split('-');
return parts[1] + '/' + parts[2] + '/' + parts[0];
};
var formattedDateFrom = formatDateString(valueFrom);
//get the text from the second textbox (to date)
//convert the string into the right format
var valueTo = document.getElementById('selected-submittedDate-to').value;
var formatDateStringTo = function (unformatted) {
var parts = unformatted.split('-');
return parts[1] + '/' + parts[2] + '/' + parts[0];
};
var formattedDateTo = formatDateStringTo(valueTo);
//just make some new variables and set the formatted dates to them
// date from, date to
var dateFrom = formattedDateFrom;
var dateTo = formattedDateTo;
//get the table row, then get the table cell,
var TableRow = document.getElementById("applicant_data");
var TableCells = TableRow.getElementsByTagName("td");
// get the table cell[6] which is the date
var check = TableCells[6].innerText;
//convert it to a string (i think it is anyways?)
var dateCheck = check.toString();
// remove the slashes in the strings
var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");
//log for testing
console.log(d1);
console.log(d2);
console.log(c);
//convert the strings into dates and set them as a new variable
var from = new Date(d1[2], d1[1]-1, d1[0]);
var to = new Date(d2[2], d2[1]-1, d2[0]);
var check1 = new Date(c[2], c[1]-1, c[0]);
//log them out again
console.log(from);
console.log(to);
console.log(check1);
问题出在我的输出上,请看:
["03", "04", "2014"]
["03", "05", "2014"]
["08", "19", "2013"]
Thu Apr 03 2014 00:00:00 GMT-0400 (Eastern Daylight Time)
Sat May 03 2014 00:00:00 GMT-0400 (Eastern Daylight Time)
//this date below should be August 19 2013......
Tue Jul 08 2014 00:00:00 GMT-0400 (Eastern Daylight Time)
这是怎么回事?!??? ???第三个日期正在发生变化。
答案 0 :(得分:3)
19被转换为一个月而不是8,并且通过它的外观,它会一个模运算。 19%12 = 7 减法:19 - 12 = 7因此7月。您可能需要重新安排日期,否则前两个案例的情况相同。换句话说,在new Date
来电中交换月和日。
更多细节 +(对早期错误的更正):
var check1 = new Date(c[2], c[1]-1, c[0]);
在上面的代码中,你需要做的是交换最后两个,所以你有:
var check1 = new Date(c[2], c[0]-1, c[1]);
该功能期望您给出年,月,日。