Organise dates into full weeks

I have several dates in a list. I want to organise these dates into weeks.

For example if I have each day from 2015-10-07 to 2015-10-14 then these will be ordered into a ul list. Any days that do not form a consecutive 7 days will be put into their own list. So if I also have 2015-10-18 that will be wrapped into it’s own separate ul list unless there is a day to follow (2015-10-19) in which case that will be wrapped along with the 2015-10-18 date until 7 consecutive days are available. After 7 consecutive days have been wrapped, a new ul list will begin.

This is an example of a HTML list that is generated on the page:

<div id="myDIV">

<ul id="date-list">
<li id="sale-2015-10-24" class="sale-listing"><div class="sale-view"><p>2015-10-24</p></div></li>
<li id="sale-2015-10-23" class="sale-listing"><div class="sale-view"><p>2015-10-23</p></div></li>
<li id="sale-2015-10-22" class="sale-listing"><div class="sale-view"><p>2015-10-22</p></div></li>
 ...........
</ul>
</div>

How could I make this happen?

Do you want to do it with JavaScript or PHP?
If JavaScript, then where and how your initial data (list of source dates) come from?

I could do this with both, however it would be preferred to do it with Javascript.

I currently have a calendar (fullcalendar by Adam Shaw) loaded onto a page, once a date on the calendar is checked then that is put into an array (selectedDays), I then sort the array and output the dates using the following:

 function sortDates(a, b)
{
 return new Date(b).getTime() - new Date(a).getTime();
}

           var sorted = selectedDays.sort(sortDates);

                                         	        var vPool="";
    jQuery.each(sorted, function(i, val) {
      vPool += '<li id="sale-'+ val +'" class="sale-listing"><div class="sale-view"><p>' + val +'</p></div></li>';
    });

   //We add vPool HTML content to #date-list
   $('#date-list').html(vPool);

Here is an example that I made for you: http://jsfiddle.net/g3nabqte/2/
Hope I’ve understood you right

1 Like

You’re awesome, thank you very much!

Hi megazoid, I’m having a little difficulty with the code you provided. Everything works fine until the 25-26th October 15, then it puts these two dates on new rows even though they’re consecutive. I’m presuming this is due to the clocks go back 1 hour on the 25th. Here is what is happening - http://jsfiddle.net/g3nabqte/3/ have you got any idea how to stop it doing this?

Hi
I don’t see that problem, maybe due to my timezone
Anyway, try to replace the number 86400000 here

if (!lastDate || (currentDate - lastDate > 86400000) || sequenceLength > 7){

with either 82800000 or 90000001 to see which of them helps

1 Like

90000001 works thank you!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.