0

I am trying to get week number(1,2,3,4,5) with in the month from Jquery UI datepicker. I googled and get the code of iso8601Week but not normal week number.

Kindly Help

user375947
  • 130
  • 12

1 Answers1

1

This should give you close to what you want, although I've only smoke tested it and there are probably some more edge conditions that need to be addressed.

I basically took the iso8601Week of the first day of the month, and subtracted it from that of the selected date. That works as is for most dates, but ISO 8601 puts days before Jan 4th in the previous year if they fall before Thursday. That's the reason for the % 52.

The code assumes an input called testDate and a label called label1:

$('#testDate').datepicker({
    onSelect: function(dateText, inst) {
        var d = new Date(dateText);
        var d1 = new Date(d.getFullYear(), d.getMonth(), 1)
        var x = $.datepicker.iso8601Week(d) % 52;
        var y = $.datepicker.iso8601Week(d1) % 52;
        $('#label1').text(x-y+1);
    }
});

I left in all the variables with partial results in them so you could tinker around with the values. This code assumes that the week begins on Monday (which is the ISO 8601 standard), and that partial weeks before Monday are week 1. So, if the month begins on a Monday, the first Monday is in week 1, and if the month begins on any other day, the first Monday is in week 2. Which looks a bit strange if the 2nd of the month is on Monday and also in week 2, but if you don't like that, you'll have to spend some time deciding in detail what you do like.

BobRodes
  • 5,990
  • 2
  • 24
  • 26
  • Thanks, This is what I exactly look for. It works according to ISO 8601 standard. I tested on month May 2016 which has 6 weeks and it worked perfectly fine. – user375947 Jul 24 '16 at 15:09
  • Glad it worked out for you. But if I might suggest it, I would test the weeks in January and December pretty thoroughly if you haven't already. – BobRodes Jul 24 '16 at 20:23