Reputation: 785
I have successfully managed (with the help from stack overflow) to loop through a calendar starting from may until end oktober 2015. now i want to highlight the current date which is 28 june sunday. but for some reason it highlights the wrong date and i don't think its because of the code but i am not a 100% sure.
checkout this link to see it visually (http://gyazo.com/30e448d0f84c8f1c55e4dd1ce6d91f38)
jsfiddle link: https://jsfiddle.net/GY22/vqfk8yLL/
this is my html code:
<ul id="timeline">
<li></li>
</ul>
this is my javascript code:
<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';
Upvotes: 1
Views: 494
Reputation: 390
Consider using MomentJS instead. It would save you a lot of code and date problems:
If you prefer to keep your code, move your current date logic inside your addListItem() method.
if(today == formatDate(new Date())) {
createListItem.className += ' currentDate';
}
Upvotes: 0
Reputation: 24
Change the last line from:
getElementsByTagName('li')[(new Date()).getDate() - 1].className += ' currentDate';
To:
getElementsByTagName('li')[(new Date()).getDate() + 1].className += ' currentDate';
The date appeared to be off by just one day before, so that should fix it.
Upvotes: 1