Geo
Geo

Reputation: 256

Calculate amount of weeks after a certain date

Im currently trying to calculate the amount of periods (each period is 1 week, after a certain date or day). Lets say first period start on 01-01-2013 (tuesday) until 29-01-2013 (tuesday)(4 periods in total).

I have a table that looks like:

id | startDate (datetime) | endDate (datetime)

I have two input fields where a user can fill in a start date and end date. I would like to fill any date between 01-01-2013 and 29-01-2013 and decide how many times it passes a tuesday (the date the period starts) again.

So if I would select 01-01-2013 until 07-01-2013 would result in: 1, but if i would select 06-01-2013 till 09-01-2013 this would result in 2 and 06-01-2013 till 16-01-2013 would result in 3 etc.

To be clear, I dont want to know the amount of weeks between the two dates, only the amount of times it 'crosses' the same day (tuesday) that was given in the database. Every period is 1 week. Is there anyone that could help me out?

Upvotes: 1

Views: 318

Answers (2)

ShuklaSannidhya
ShuklaSannidhya

Reputation: 8976

Use PHP's date() function.

$startday = strtotime($start_date_from_db);//date from db;
$endday = strtotime($end_date_from_db);//date from db;
$counter = 0;
for($i=$startday; $i<=$endday; $i+=86400) {
    $current_day = date('w', $i);
    if($current_day == 2) { //0 for sunday, 1 for monday, 2 for tuesday
        $counter++;
    }
}

Upvotes: 2

Naryl
Naryl

Reputation: 1888

When comparing dates a good method is:

1- transform the dates to timestamps:

$timestamp1 = strtotime($date1);
$timestamp2 = strtotime($date2);

2- do the desired operation, in this case:

$timebetween = $timestamp2 - $timestamp1;

3- Transform result (number of seconds) to desired value, in this case:

$weeks= $timebetween / 604800;

Upvotes: 1

Related Questions