我已经成功管理(在堆栈溢出的帮助下)循环从5月开始到2015年5月底的日历。现在我想突出显示当前日期是6月28日星期日。但由于某种原因,它突出了错误的日期,我不认为它是因为代码,但我不是100%肯定。
结帐此链接以直观地看到它(http://gyazo.com/30e448d0f84c8f1c55e4dd1ce6d91f38)
jsfiddle链接:https://jsfiddle.net/GY22/vqfk8yLL/
这是我的HTML代码:
<ul id="timeline">
<li></li>
</ul>
这是我的javascript代码:
<script>
// Get today's current date.
var now = new Date();
console.log(now);
// Calculates the number of the week
var weekNumber = ((now.getDate()<10) ? "0" : "")+ now.getDate();
console.log("The current week number is: " + weekNumber);
// Array list of months.
var month = new Array(12);
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
//console.log(month[3]);
var weekDay = new Array(7);
weekDay[0]= "Su";
weekDay[1] = "Mo";
weekDay[2] = "Tu";
weekDay[3] = "We";
weekDay[4] = "Th";
weekDay[5] = "Fr";
weekDay[6] = "Sa";
function formatDate(date) {
var month = date.getUTCMonth() +1;
var dayNumber = date.getUTCDate();
var year = date.getUTCFullYear();
var day = date.getUTCDay();
return weekDay[day] + ": " + dayNumber + "-" + month + "-" + year + "; ";
//return weekDay[day] + " " + dayNumber + "; ";
}
//console.log(formatDate(new Date()));
var today
function addListItem(){
var createListItem = document.createElement("li");
var outputListItem = document.createTextNode(today);
createListItem.appendChild(outputListItem);
var createUl = document.getElementsByTagName("ul");
createUl[0].appendChild(createListItem);
}
// loop starting from may up untill for months from the set date
for (var i = 0; i < 122; i++){
today = formatDate(new Date(2015, 05, i));
//document.write(today + "<br />");
addListItem();
}
document.getElementById('timeline').
getElementsByTagName('li')[(new Date()).getDate() - 1].className += ' currentDate';
答案 0 :(得分:1)
更改最后一行:
getElementsByTagName('li')[(new Date()).getDate() - 1].className += ' currentDate';
要:
getElementsByTagName('li')[(new Date()).getDate() + 1].className += ' currentDate';
日期似乎在一天之前关闭,所以应该修复它。
答案 1 :(得分:0)
考虑使用MomentJS。它可以为您节省大量的代码和日期问题:
如果您希望保留代码,请在addListItem()方法中移动当前日期逻辑。
if(today == formatDate(new Date())) {
createListItem.className += ' currentDate';
}