1

I found a javascript and a php script to get current week of the month base on the entire year. That's great but im a little confused. I would like to know whether if it's week 1,2,3,4 of current month not entire year. How should I got about that?

javascript

/**
 * Returns the week number for this date.  dowOffset is the day of week the week
 * "starts" on for your locale - it can be from 0 to 6. If dowOffset is 1 (Monday),
 * the week returned is the ISO 8601 week number.
 * @param int dowOffset
 * @return int
 */
Date.prototype.getWeek = function (dowOffset) {
/*getWeek() was developed by Nick Baicoianu at MeanFreePath: http://www.meanfreepath.com */

    dowOffset = typeof(dowOffset) == 'int' ? dowOffset : 0; //default dowOffset to zero
    var newYear = new Date(this.getFullYear(),0,1);
    var day = newYear.getDay() - dowOffset; //the day of week the year begins on
    day = (day >= 0 ? day : day + 7);
    var daynum = Math.floor((this.getTime() - newYear.getTime() - 
    (this.getTimezoneOffset()-newYear.getTimezoneOffset())*60000)/86400000) + 1;
    var weeknum;
    //if the year starts before the middle of a week
    if(day < 4) {
        weeknum = Math.floor((daynum+day-1)/7) + 1;
        if(weeknum > 52) {
            nYear = new Date(this.getFullYear() + 1,0,1);
            nday = nYear.getDay() - dowOffset;
            nday = nday >= 0 ? nday : nday + 7;
            /*if the next year starts before the middle of
              the week, it is week #1 of that year*/
            weeknum = nday < 4 ? 1 : 53;
        }
    }
    else {
        weeknum = Math.floor((daynum+day-1)/7);
    }
    return weeknum;
};

Usage

var mydate = new Date(2011,2,3); // month number starts from 0
// or like this
var mydate = new Date('March 3, 2011');
alert(mydate.getWeek());
Community
  • 1
  • 1
Sebastian Farham
  • 815
  • 2
  • 13
  • 27
  • Have you tried anything? I would suggest taking these two scripts and at least giving an attempt to work out your problem, rather than asking someone to code for you. – Tony Mar 29 '17 at 23:04
  • @Tony: Trying something now. – Sebastian Farham Mar 29 '17 at 23:12
  • @Tony: Be nice if you would remove your downvote. – Sebastian Farham Mar 29 '17 at 23:34
  • I cant until you edit your initial post. I would suggest a simple edit or something? I've tried removing my down vote already. "You last voted on this question 35 mins ago. Your vote is now locked in unless this question is edited." – Tony Mar 29 '17 at 23:35
  • if you have example code, like in your answer to your own question, why wouldn't you put the code in the question? – Jaromanda X Mar 29 '17 at 23:36
  • How do you define the week of the month? e.g. ISO defines the week of the year to based on the first Thursday and week of month on first Monday. – RobG Mar 30 '17 at 04:10

2 Answers2

2

This works at getting the current week of the month for those who only want to know which week from 1 to 5.

script

var d = new Date();
var date = d.getDate();
var day = d.getDay();

var weekOfMonth = Math.ceil((date + 6 - day)/7);

document.getElementById('week').value = weekOfMonth;

markup

<input type='text' id='week' value=''>
Sebastian Farham
  • 815
  • 2
  • 13
  • 27
  • this would produce weeks 0 - 4 ... perhaps `date + 6 - day` to get 1 - 5? – Jaromanda X Mar 29 '17 at 23:35
  • but there are more than 28 days in most months - so 1 - 4 will never be accurate (that would imply 48 weeks in a year) – Jaromanda X Mar 29 '17 at 23:48
  • @JaromandaX Right. I will edit and work around it so that it fit the program. – Sebastian Farham Mar 29 '17 at 23:51
  • 1
    This algorithm is based on the first week starting on the first of the month, which might be any day of the week. The ISO 8601 standard uses the week in which the first Monday occurs, so where Monday is not the first of the month, there will be days in the week that belong to the last week of the previous month. E.g. this algorithm says 2017-03-02 is in week 1 of March but ISO says it's in week 4 of February. – RobG Mar 30 '17 at 04:37
1

The ISO week in month number is based on Mondays, so Thursday, 2 March 2017 is in week 4 of February 2017 and Monday 6 March 2017 is in week 1 of March.

So the algorithm is to move to the previous Monday and see which Monday of the month it is. I would have thought this was a duplicate but I can't find one, so here's a function.

/* Get ISO week in month, based on first Monday in month
** @param {Date} date - date to get week in month of
** @returns {Object} month: month that week is in
**                   week: week in month
*/
function getISOWeekInMonth(date) {
  // Copy date so don't affect original
  var d = new Date(+date);
  if (isNaN(d)) return;
  // Move to previous Monday
  d.setDate(d.getDate() - d.getDay() + 1);
  // Week number is ceil date/7
  return {month: +d.getMonth()+1,
          week: Math.ceil(d.getDate()/7)};
}
//*
[new Date(2017,2,2),   // Thu 2 Mar 2017
 new Date(2017,2,6),   // Mon 6 Mar 2017
 new Date(2017,4,31),  // Wed 31 May 2017
 new Date()].forEach(  // Current date
  function(date) {
    console.log(date.toString() + '\nis in week ' +
    getISOWeekInMonth(date).week + ' of month ' +
    getISOWeekInMonth(date).month);
  }
);
//*/

If you want to get the ISO week in the year, then Get week of year in JavaScript like in PHP has your answer.

RobG
  • 142,382
  • 31
  • 172
  • 209
  • Can you tell me how to use a simplified more dynamic version of your code (no hardcoded dates)? I only need the integer to print in an input like in my code. I'll mark you as answer. Thank you – Sebastian Farham Apr 03 '17 at 18:44
  • @SebastianFarham—The function is only 4 lines of code, I think that's simple enough. It uses any date you wish to pass to it. If you want just the week number, then reduce the return to `Math.ceil(d.getDate()/7)`. – RobG Apr 03 '17 at 20:26
  • I did try this. Then I tried to print an input -> document.getElementById('week').value = d; and blank. – Sebastian Farham Apr 03 '17 at 22:36
  • @SebastianFarham—code added after a return doesn't get executed. See [*updated fiddle*](https://fiddle.jshell.net/2sz432uq/5/). – RobG Apr 04 '17 at 02:21
  • @Strange I did try something similar to what you did in the recent fiddle but hey thanks a lot Rob. – Sebastian Farham Apr 04 '17 at 17:57