How many weeks are inside of two dates - php

I have starting dates and ending dates in my database (MySQL).
How can I get the answer, how many weeks(or days) are inside of those 2 dates? (mysql or php)
For example I have this kind of database:
Started and | will_end
2009-12-17 | 2009-12-24
2009-12-12 | 2009-12-26
...
Update to the question:
How to use DATEDIFF?
How can I make this to work? or should I use DATEDIFF completly differently?
SELECT DATEDIFF('Started ','will_end') AS 'Duration' FROM my_table WHERE id = '110';

If the two columns $d1 and $d2 store unix timestamp obtained from time() then this simple line suffices:
$diffweek = abs($d1 - $d2) / 604800;
Otherwise if the columns are of DATETIME type, then:
$diffweek = abs(strtotime($d1) - strtotime($d2)) / 604800;
p/s: 604800 is the number of seconds in a week (60 * 60 * 24 * 7)
p/s2: you might want to intval($diffweek) or round($diffweek)

Calculating the number of days and dividing by seven won't give you the number of weeks between the two dates. Instead it will return the result of division by 7 that doesn't always correspond to the number of weeks between the two dates when thinking in terms of the number of weeks in the ISO calculation.
For example, given start_date = "2010-12-26" and end_date = "2011-01-25" you will be going through W51,52,01,02,03,04 and those are 6 weeks as per ISO, but if you simply calculate the difference and divide by 7, you'll get 5.
The issue appears when the start date and end date belong to different years.
The best way to do the calculation is to get the last week number of the start_date year and it should refer to the December, 28.
function weeks($ladate2,$ladate3) {
$start_week= date("W",strtotime($ladate2));
$end_week= date("W",strtotime($ladate3));
$number_of_weeks= $end_week - $start_week;
$weeks=array();
$weeks[]=$start_week;
$increment_date=$ladate2;
$i="1";
if ($number_of_weeks<0){
$start_year=date("Y",strtotime($ladate2));
$last_week_of_year= date("W",strtotime("$start_year-12-28"));
$number_of_weeks=($last_week_of_year-$start_week)+$end_week;
}
while ($i<=$number_of_weeks)
{
$increment_date=date("Y-m-d", strtotime($ladate2. " +$i week"));
$weeks[]=date("W",strtotime($increment_date));
$i=$i+1;
}
return $weeks;
}
function diff_weeks($ladate2,$ladate3) {
$weeks=weeks($ladate2,$ladate3);
$diff_weeks=count($weeks);
return $diff_weeks;
}
Best regards,
Manikam

MySQL has datediff which returns the difference in days between two dates, since MySQL 4.1.1.
Do note that, as per the manual, DATEDIFF(expr1,expr2) returns expr1 – expr2 expressed as a value in days from one date to the other. expr1 and expr2 are date or date-and-time expressions. Only the date parts of the values are used in the calculation.

You can use the TO_DAYS function on each date and subtract the two to calculate the difference in days.

DATEDIFF
Find the days and divide by 7

<?php
$dayDif = date('z',strtotime('2009-12-17)') - date('z',strtotime('2009-12-24)');
$numWeeks = $dayDif / 7;
?>
The z option for php's date function gives you the day of the year (0 - 365). By subtracting the two values you find how many days between dates. Then factor by seven for the number of weeks.
Read this page closely, the date() function is rich. http://php.net/manual/en/function.date.php

Related

Calculate how many days (Monday - Wednesday) between two dates - Woocommerce Bookings?

I am struggling with the price calculation of Woocommerce Bookings for the type "days". If the price on a daterange (e.g. Monday to Wednesday or Wednesday-Saturday or Sunday-Tuesday...) is higher than on the other days.
So far I know how many days:
$days = date_diff($from, $to)->format('%d');
This question helps to get the number of single days: calculate sundays between two dates
But how do I get not only "sundays" but every daterange (e.g. from 6 to 2) with this:
$sundays = intval($days / 7) + ($from->format('N') + $days % 7 >= 7);
I guess I need to iterate through daterange and use this formula but I cannot figure out how.
You can use a completely different approach:
Create a DatePeriod object and loop through the Period object and increment a variable each time you encounter the range.
The following code achieve it but only return the number of complete range:
$from='2018/09/1';
$to='2018/09/31';
$start='Sunday';
$end='Thursday';
$go=false;
$period=new DatePeriod(date_create($from),date_interval_create_from_date_string('1 days'),date_create($to));
$nRange=0;
foreach($period as $date){
if($date->format('l')===$start){
$go=true;
}
if($go&&$date->format('l')===$end){
$go=false;
$nRange++;
}
}
print_r($nRange);
output :
4
It works fine for any chosen range.
However if the need is to get any valid day within the given range complete or not you can alter the previous code this way:
$from='2018/09/17';
$to='2018/09/31';
$start='Sunday';
$end='Thursday';
$day_num=['Monday'=>1,'Tuesday'=>2,'Wednesday'=>3,'Thursday'=>4,'Friday'=>5,'Saturday'=>6,'Sunday'=>7];
$start_num=$day_num[$start];
$end_num=$day_num[$end];
$period=new DatePeriod(date_create($from),date_interval_create_from_date_string('1 days'),date_create($to));
$nRange=0;
if($start_num===$end_num){
$valid_range=array_values($day_num);//keep the number of each day of the week
}
elseif($start_num>$end_num){
$valid_range=array_values($day_num);//keep the number of each day of the week
while($valid_range[0]!==$start_num){//rotate the values to keep the start day first
$pop=array_shift($valid_range);
array_push($valid_range,$pop);
}
$valid_range=array_slice($valid_range,array_search($start_num,$valid_range),$start_num-$end_num);//keep only the days in the chosen range
}else{
$valid_range=array_values($day_num);//keep the number of each day of the week
$valid_range=array_slice($valid_range,array_search($start_num,$valid_range),$end_num-$start_num); //keep only the days in the chosen range
}
$valid_range=array_flip($valid_range);//flip the array to make the search more fast
foreach($period as $date){
if(isset($valid_range[(int)$date->format('N')])){
$nRange++;
}
}
print_r($nRange);//output the number of valid days
ouput:
6

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?
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++;
}
}
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;

AVG datetime interval, show Days and Hours

I'm trying to calculate an average interval between TIMESTAMP (YY-MM-DD HH:MM:SS) records in a column (hit_date) from a table.
I did this in MySql:
SELECT DATEDIFF(MAX(hit_date), MIN(hit_date)) / (COUNT(hit_date) - 1) AS hitavg FROM my_table
This returns a value, ie 135.50.
Then, I did this in PHP to show results:
$value = ($res_from_mysql_query);
$days = (int) $value;
$hours = 24 * ($value - $days);
echo "$days Days, $hours Hours";
and my result is:
135 Days, 0 Hours.
But this is not the correct result... what's wrong?
Have I to use TIMEDIFF in MySql? If yes, I got a total different value... so, how can I implement my PHP script?
How can I correctly show Days and Hours for this interval?
Please, help me to improve this, any help would be really appreciated!
what about like that code:
SELECT TIMESTAMPDIFF(HOUR, MIN(hit_date), MAX(hit_date)) / (COUNT(*)-1) AS hitavg FROM my_table
TIMESTAMPDIFF(UNIT, DATETIMEEXP1, DATETIMEEXP2) returns the difference in HOURS between DATETIMEEXP1 and DATETIMEEXP2.. for each "select" the query finds the date of first and last hit (visit) and total visit's count, then calcute arithmetic average.
Then in PHP is easy way to display the difference...
Maybe you should look at these MySQL ref:
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timediff

Figuring out the difference in days between events

I have a MySQL DB with StartDates in the format of yyyy-mm-dd and starttimes in the format of HH:MM using a 24 hour clock. What would be the easiest way to compare the difference of two days in PHP? Would using a datetime object could I set it to be with the information given and just give it to zeros for the seconds? I need to get the amount of time between both dates down to the minute. I was putting the startdate (Just the day since its always within the same month for my application) and time together concatenated together and then pulling out what I need like below, but I haven't been able to get it straight yet. Thanks for the look!
$tempvar1 = $times[$i][$j];
$tempvar2 = $times[$i][$j+1];
$day1 = $tempvar1[0].$tempvar1[1];
$day2 = $tempvar2[0].$tempvar2[1];
$hours1 = $tempvar1[2].$tempvar1[3];
$hours2 = $tempvar2[2].$tempvar2[3];
$minutes1 = $tempvar1[5].$tempvar1[6];
$minutes2 = $tempvar2[5].$tempvar2[6];
$numdays = ($day2-$day1) - 1;
$time1 = ($hours1*60)+$minutes1;
$time2 = ($hours2*60)+$minutes2;
MySQL has plenty of date/time functions:
SELECT TIMEDIFF(endtime, starttime), DATEDIFF(endtime, starttime)
FROM ...
doc links for timediff and datediff
That'll you get strings in the format of 'hh:mm:ss.ssss' for timediff, and a straight-up integer representing the days between the two dates, respectively.

caculating dates with php

I have a general question on calculating dates with php.
What happens if I store a timestamp like this in my database:
$db_timestamp = '2010-01-31 00:00:00';
and then run a daily script that checks if a month has passed since the timestamp was saved in the database:
if ($db_timestamp == make_unix_timestamp(mktime(0, 0, 0, date("m") - 1, date("d"), date("Y")), TRUE, 'eu')))
{
do something
};
my problem is that i just realized that this wouldn't work for all dates. in this case 'do something' would not be called in February, since February doesn't have a 31st day. any idea on how to implement something like that?
First, your DBMS should have a data type for date/time. They all store timestamps in a similar way.
MySQL then provides a function called UNIX_TIMESTAMP() if you need to return a timestamp PHP can understand.
SELECT UNIX_TIMESTAMP(`createTime`) FROM `articles`;
The opposite function is called FROM_UNIXTIME():
INSERT INTO `articles` (`createTime`) VALUES ( FROM_UNIXTIME(12345678) );
MySQL (or another DBMS for that matter, but I'm using MySQL as an example) has a slew of other functions to calculate time differences. For example, to know if an article is more than one month old, use can use DATE_SUB():
SELECT * FROM `articles`
WHERE `article`.`createTime` <= DATE_SUB(NOW(), INTERVAL 1 MONTH);
(In MySQL5 and above, you can also write it as such)
SELECT * FROM `articles`
WHERE `article`.`createTime` <= (NOW() - INTERVAL 1 MONTH);
$ts = strtotime($db_timestamp);
if ($ts < (time() - 2592000))
{
do something;
}
2592000 seconds = 30 days
You could use date_diff http://us3.php.net/manual/en/datetime.diff.php
or do a comparison of the timestamp in your database with
strtotime("-1 month");
You could check the timestamp using a query:
MySQL:
select date from table where date < now() - INTERVAL 1 MONTH;
It kind of depends on how you consider "one month".
If "one month" means "30 days", a solution would be to compare the timestamp you get from the database with the current timestamp :
$db_timestamp = strtotime('2010-01-31');
$current_timestamp = time();
var_dump( ($current_timestamp - $db_timestamp) / (24*3600) );
If the difference is 30 days... that's it.
A couple of notes :
strtotime converts a date to an UNIX timestamp-- i.e. the number of seconds since 1970-01-01
time returns the current UNIX timestamp
you can compare timestamps : they only represent a number of seconds ; and there are 24*60*60 seconds per day ;-)

Categories