AVG datetime interval, show Days and Hours - php

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

Related

calculate difference between two date with php time() function in mysql query

I have searched about this but I could not find anything.
I have a article table. when I write new article I write time into mysql table with using php time() function.
my table is
id article time
time data type is INT(UNSIGNED)
my problem is I want to show articles from last week to today or from last month to today.
how my mysql query should be?
normally I do this
SELECT * FROM articles ORDER BY Time DESC
so this gives me data from today to past. how should I do this? I can't come up with a solution. should I use php-mysql together or can I handle this with only mysql? could you give me idea or example please? thanks.
edit:
I changed to datetime as suggested and now I think I have timezone problem
now my ago() function work 2 hours late.
<?php
date_default_timezone_set('Europe/Istanbul'); //timezone function
ago($time)
{
$periods = array("saniye", "dakka", "saat", "gün", "hafta", "ay", "yıl", "baya");
$lengths = array("60","60","24","7","4.35","12","10");
$now = time();
$difference = $now - $time;
$tense = "önce";
for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
$difference /= $lengths[$j];
}
$difference = round($difference);
return "$difference $periods[$j] önce ";
} //ago function
echo $Date = ago(strtotime($data['WriteTime'])). 'önce';
?>
Assuming your time column is a Unix timestamp, you can try something like this: (not tested)
SELECT ...
FROM magic
WHERE `time` BETWEEN DATE_SUB(FROM_UNIXTIME(`time`), INTERVAL 1 WEEK) AND NOW()
For your month, you would use INTERVAL 1 MONTH. Please, convert your column to common data types and don't use reserved words as the column names.
First make time a date type field
(and give it a meaningful different name like article_date for e.g)
Then use this query:
SELECT * FROM articles
WHERE article_date BETWEEN CURDATE() - INTERVAL 7 DAY AND CURDATE()
Well, you made a beginner mistake in using the unix timestamp integer for storage in your database. You should almost always use a date/datetime field type, because you invariably need to query against those fields which is much easier when not using unix timestamps.
So, convert your field to datetime, use MySQL's NOW() to insert current timestamps into the field when adding rows.
Then look at the MySQL data/time functions to query against thus field to your heart's desire.
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html

Average days from dates Mysql, PHP [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Calculate DateDiff in SQL in Days:Hours:Mins:Seconds format
I have this MySql query:
SELECT DATEDIFF(MAX(hit_date), MIN(hit_date)) / (COUNT(hit_date) - 1) AS hitavg FROM my_table
This returns a value (average days between recorded rows from hit_date column, this column is in TIMESTAMP format, so YY:MM:DD HH:MM:SS)
Assuming that this value is 385.500 (returned from the query), how can I format in PHP this number as 385 Days, "n" Hours (where "n" is the decimal value, in this case 500)?
Thanks in advance to all!
Well, if you only want Days and Hours, then:
$value = 385.500;
$days = (int) $value;
$hours = 24 * ($value - $days);
echo "$days Days, $hours Hours";

today and not last 24 hours?

i my php codes i do time()-86400 to fetch everything from the last 24 hours, but how i can get everything today or everything from yesterday. thus it is no longer 86400 seconds, it should be after 12 midnight till current time.
hope this makes sense.. but how i can do this?
If you are "fetching" from a database, why not do it in the query?
SELECT * FROM `table` WHERE DATE(`created_at`) = '2011-03-28';
If you are storing the date as a unix timestamp:
SELECT * FROM `table` WHERE DATE(FROM_UNIXTIME(`created_at`)) = '2011-03-28';
time()-strtotime('today') - difference between now and midnight; time()-strtotime('yesterday') - difference between now and yesterday midnight; time()-strtotime('-2 days')...
for yesterday only (range $min to $max)
$start = strtotime('yesterday')
$end = strtotime('today') - 1;
etc.
Following will give you the seconds passed since January 1, 1970. Every object with a timestamp higher than this value is from the current day (given that you have set your timezones and local time correctly).
$time = strtotime(date('Y-m-d 00:00:00'));
You can use the PHP date and strtotime function in order to pick a day from now and retrieve the seconds that specific date. For more info, see: http://php.net/manual/en/function.date.php and http://php.net/manual/en/function.strtotime.php
I agree with Gordon here - there are so many date/time examples. But hey, let's go over it again - assuming today begins at midnight, you use:
$start = strtotime('today');
Assuming "today" ends at 23:59, simple arithmetics imply that if you increment the $start by 24 hours and take away 1 second - you'll reach the end of today.
So:
$start = strtotime('today');
$end = $start + (3600 * 24) - 1;

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 ;-)

How many weeks are inside of two dates

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

Categories