October 8, 2012
How to week of the year and use it as image source?
Question by Will Gibbons
What I am trying to do is show a jpg for each week in the year depending on what the date is. Does anybody know why this does not work?
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
}
var weekNumber = (new Date()).getWeek();
var test='<img src="C:/temp/ + weekNumber + .jpg"/>';
document.write(test);
Answer by Starx
Here is a function to get the week number.
function getWeekNumber(d) {
// Copy date so don't modify original
d = new Date(d);
d.setHours(0,0,0);
// Set to nearest Thursday: current date + 4 - current day number
// Make Sunday's day number 7
d.setDate(d.getDate() + 4 - (d.getDay()||7));
// Get first day of year
var yearStart = new Date(d.getFullYear(),0,1);
// Calculate full weeks to nearest Thursday
var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7)
// Return array of year and week number
return weekNo;
}
Credit: RobG
Use the above function to get the number and use in your script
weekNumber = getWeekNumber(new Date());
var test='<img src="C:/temp/' + weekNumber + '.jpg"/>';
document.write(test);