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

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

Related

PHP - Time based math

How exactly is this done? There's so many questions on stack-overflow about what I'm trying to do; However all of the solutions are to edit the MYSQL Query, and I need to do this from within PHP.
I read about the strtotime('-30 days') method on another question and tried it, but I can't get any results. Here's what I'm trying:
$current_date = date_create();
$current_date->format('U');
... mysql code ...
$transaction_date = date_create($affiliate['Date']);
$transaction_date->format('U');
if($transaction_date > ($current_date - strtotime('-30 days'))) {
} else if(($transaction_date < (($current_date) - (strtotime('-30 days'))))
&& ($transaction_date > (($current_date) - (strtotime('-60 days'))))) {
}
Effectively, I'm trying to sort all of the data in the database based on a date, and if the database entry was posted within the last 30 days, I want to perform a function, then I want to see if the database entry is older than 30 days, but not older than 60 days, and perform more actions.
This epoch math is really weird, you'd think that getting the epoch of the current time, the epoch of the data entry, and the epoch of 30 and 60 days ago would be good enough to do what I wanted, but for some reason it's not working, everything is returning as being less than 30 days old, even if I set the date in the database to last year.
No need to convert to unix timestamp, you can already compare DateTime objects:
$current_date = data_create();
$before_30_day_date = date_create('-30 day');
$before_60_day_date = date_create('-60 day');
$transaction_date = date_create($affiliate['Date']);
if ($transaction_date > $before_30_day_date) {
# transation date is between -30 day and future
} elseif ($transaction_date < $before_30_day_date && $transaction_date > $before_60_day_date) {
# transation date is between -60 day and -30 day
}
This creates (inefficiently, see my comment above) an object:
$current_date = date_create(date("Y-m-d H:i:s"));
From which you try to subtract an integer:
if($transaction_date > ($current_date - strtotime('-30 days'))) {
which is basically
if (object > (object - integer))
which makes no sense.
you're mixing the oldschool time() system, which deals purely with unix timestamps, and the newer DateTime object system, which deals with objects.
What you should have is
$current_date = date_create(); // "now"
$d30 = new DateInterval('P30D'); // 30 days interval
$transaction_date = date_create($affiliate['Date']);
if ($transaction_date > ($current_date->sub($d30)) { ... }
You might consider DatePeriod class, which in essence gives you the ability to deal with a seires of DateTime objects at specified intervals.
$current_date = new DateTime();
$negative_thirty_days = new DateInterval::createFromDateString('-30 day');
$date_periods = new DatePeriod($current_date, $negative_thrity_days, 3);
$thirty_days_ago = $date_periods[1];
$sixty_day_ago = $date_periods[2];
Here you would use $thirty_days_ago, $sixty_days_ago, etc. for your comparisons.
Just showing this as alternative to other options (which will work) as this is more scalable if you need to work with a larger number of interval periods.

Check if datetime value is from last 30 days in php (not in the mysql query)?

I need to check with php if values got from a database are from last 30 days.
The values are formatted as follows:
2012-03-19 05:00:32
How can this be done?
You can use strtotime to turn it to a unix timestamp.
$db_date = "2012-03-19 05:00:32";
if (time() - strtotime($db_date) <= 30 * 86400) {
//...
}
$date = '2012-03-19 05:00:32';
if (strtotime($date) >= strtotime('-30 days')) {
// do something
}
See strtotime() reference.
You could do it in PHP, but that'd mean a roundtrip through the date/time system to process that string back into a date value:
$within_30 = ((strtotime('2012-03-19 05:00:32') + 30*86400) > time());
Assumign you're using MySQL, you could do it in the query directly, and save some time conversions:
SELECT ((yourtimefield + INTERVAL 30 DAY) > now()) AS within_30 ...

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.

Date comparison with PHP and Mysql

I have a table with a date field type date.
What I am trying to do is to do a comparison between the date from inside the table and the today date. If the date from the table is yesterday then insert the today date.
The thing I'm not sure about is how to insert the data in the database so I can make the comparison. here is what im thinking to do"
$d = time();
$x = mysql_querry("SELECT date FROM table where id = $id", $con);
while($y = myqsl_fetch_array($x)){
$oldTime = $y['date'];
}
if ($oldTime < $d){
$i = mysql_querry("INSERT INTO table (date) VALUES (CURDATE()) ", $con);
}
So, I'm not sure if $oldTime and $d can be compared like that, but I hope you guys get my point.
Any ideas?
Thanks
You can't do in that way because the CURDATE() function return a date in a format like 2011-11-11 while time() returns the number of seconds since the January 1 1970 00:00:00 GMT.
Anyway you can change the format of the time() to look like the CURDATE() using the date() function in this way:
date('Y-m-d', time())
or even better, to get the current date, you can use just this line:
date('Y-m-d')
To conclude, you can do the if in this way:
if( strtotime($oldTime) < strtotime(date('Y-m-d')) )
or even better:
if( strtotime($oldTime) < strtotime('now') )
To compare dates you can use strtotime($date); Where date can be a time(), mysql date or date('Y-m-d'); string

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