Reputation: 17382
I want to print the week,year in HTML, ie 43,2013
. Also when I press prev
button it should print 42,2013
and on pressing next I should get 44,2013
.
I'm able to do it for month,year ie October,2013
and getting next presvious months but unable to do it for week.
Here is my code for month. Kindly help me in writing the code for week.
function monthNav(nav) {
if(nav == 'prev') {
var newMonth = cur_dat.getMonth() - 1;
var newYear = cur_dat.getFullYear();
if(newMonth < 0) {
newMonth = 11;
newYear -= 1;
}
cur_dat.setMonth(newMonth);
cur_dat.setFullYear(newYear);
curMonthYear = month[newMonth] + ", " + newYear;
$("#mNav").html(curMonthYear);
} else {
var newMonth = cur_dat.getMonth() + 1;
var newYear = cur_dat.getFullYear();
if(newMonth > 11) {
newMonth = 0;
newYear += 1;
}
if(newYear == curYear && newMonth > curMonth) {
return false;
}
cur_dat.setMonth(newMonth);
cur_dat.setFullYear(newYear);
curMonthYear = month[newMonth] + ", " + newYear;
document.getElementById('periodVal').value=curMonthYear;
$("#mNav").html(curMonthYear);
}
}
Upvotes: 0
Views: 1084
Reputation: 1
I am able to get the desired results using the following. The key thing is to do the addition of the days and the division as two sep functions - otherwise I was getting crazy results.
var weeksCount = function (year, month_number) {
var firstOfMonth = new Date(year, month_number, 1);
var day = firstOfMonth.getDay();
var lastOfMonth = new Date(year, month_number + 1, 0);
var lastDate = lastOfMonth.getDate();
var result = day + lastDate;
result = Math.ceil(result / 7);
return result;
};
Upvotes: 0
Reputation: 1163
rubyist's function worked fine for getting the date, just changed Math.ceil to Math.floor and it works fine. I took the liberty of cleaning your original code a little.
function weekNav(nav) {
//just create a +1 or -1 valued variable here so you dont
//have to write the same code over agian.
if (nav == 'prev') {
var state = -1;
} else {
var state = 1;
}
var d = new Date();
var newWeek = cur_dat.getWeek(d) + state;
var newYear = cur_dat.getFullYear() + state;
if (newWeek < 0) {
newWeek = 52;
newYear -= 1;
} else if (newWeek > 52) {
newWeek = 0;
newYear += 1;
}
//display to HTML like monthNav()
}
/* Editted this function to adjust for last few days of the year */
function getWeeks(d) {
var first = new Date(d.getFullYear(),0,1);
var dayms = 1000 * 60 * 60 * 24;
var numday = ((d - first)/dayms);
var getDay = (numday + first.getDay()+1 )/ 7;
var weeks = Math.round(getDay);
if ((numday+first.getDay()+1/7) > 365) {
weeks++;
}
return weeks;
}
Upvotes: 0
Reputation: 3323
Try this -
function getWeeks(d) {
var first = new Date(d.getFullYear(),0,1); //start of the year
var dayms = 1000 * 60 * 60 * 24;
var numday = ((d - first)/dayms)
var weeks = Math.ceil((numday + first.getDay()+1) / 7) ;
return weeks
}
alert(getWeeks(new Date("1 Dec 2012"))); //end of the year
and check your code here http://jsbin.com/ugesex/29/edit
Upvotes: 1