I'm getting a list of items from my database, each has a CURRENT_TIMESTAMP which i have changed into 'x minutes ago' with the help of timeago. So that's working fine. But the problem is i also want a "NEW" banner on items which are less than 30 minutes old. How can i take the generated timestamp (for example: 2012-07-18 21:11:12) and say if it's less than 30 minutes from the current time, then echo the "NEW" banner on that item.
Use strtotime("-30 minutes") and then see if your row's timestamp is greater than that.
Example:
<?php
if(strtotime($mysql_timestamp) > strtotime("-30 minutes")) {
$this_is_new = true;
}
?>
I'm using strtotime() twice here to get unix timestamps for your mysql date, and then again to get what the timestamp was 30 minutes ago. If the timestamp from 30 mins ago is greater than the timestamp of the mysql record, then it must have been created more than 30 minutes go.
Try something like this, using PHP's DateTime object:
$now = new DateTime();
$then = DateTime($timestamp); // "2012-07-18 21:11:12" for example
$diff = $now->diff($then);
$minutes = ($diff->format('%a') * 1440) + // total days converted to minutes
($diff->format('%h') * 60) + // hours converted to minutes
$diff->format('%i'); // minutes
if ($minutes <= 30) {
echo "NEW";
}
Edit: Mike is right, I forgot that for whatever reason, only %a actually returns the total of its type (in this case days). All the others are for displaying time formatting. I've extended the above to actually work.
You can do like this also -
$currentTime=time();
to check the last updated time is 30 minute old or not
last_updated_at < $currentTime - (60*30)
Related
The timestamp in my database is 2015-03-03 00:25:39 (Take note that the type = timestamp and the correct current timestamp in my end is 2015-03-02 01:31:00. The difference should be around 23 hours. But now the problem is that the answers provided in the net will give me 30 hours instead of 23 hours. Some of the codes that I have tried are the following:
$target is the target date
CODE 1:
$then = strtotime($target);
$diff = $then - time();
echo sprintf("%s days and %s hours left", date('z', $diff), date('G', $diff));
But it gives me 1 days and 6 hours left. So 30 hours
CODE2:
$seconds = strtotime("$target") - time();
echo $seconds; exit();
$days = floor($seconds / 86400);
$seconds %= 86400;
$hours = floor($seconds / 3600);
echo $hours;
It gives me something like 107388 = 30 hours.
CODE 3:
//Convert to date
$datestr= $target;//Your date
$date=strtotime($datestr);//Converted to a PHP date (a second count)
//Calculate difference
$diff=$date-time();//time returns current time in seconds
$days=floor($diff/(60*60*24));//seconds/minute*minutes/hour*hours/day)
$hours=round(($diff-$days*60*60*24)/(60*60));
It gives me 6 hours
I don't know what I'm doing wrong, more like I have no idea how to do it.
This is now my last resort since I can't find the solution that will help me.
Hoping for your fast responses.
PHP's DateTime() (and DateInterval()) are much better for date math and returns the correct results:
$date = new DateTime('2015-03-03 00:25:39');
$now = new DateTime('2015-03-02 01:31:00');
$diff = $date->diff($now);
echo $diff->h, ' hours ', $diff->i, ' minutes';
Demo
This is a very late answer, but your question is a good one that will likely be searched for in the future.
Here is an online demo.
// this doesn't appreciate any timezone declarations, you'll need to add this if necessary
$target="2015-03-03 00:25:39"; // declare your input
$then=new DateTime($target); // feed input to DateTime
$now=new DateTime(); // get DateTime for Now
$diff=(array)$then->diff($now); // calculate difference & cast as array
$labels=array("y"=>"year","m"=>"month","d"=>"day","h"=>"hour","i"=>"minute","s"=>"second");
$readable=""; // declare as empty string
// filter the $diff array to only include the desired elements and loop
foreach(array_intersect_key($diff,$labels) as $k=>$v){
if($v>0){ // only add non-zero values to $readable
$readable.=($readable!=""?", ":"")."$v {$labels[$k]}".($v>1?"s":"");
// use comma-space as glue | show value | show unit | pluralize when necessary
}
}
echo "$readable";
// e.g. 2 years, 20 days, 1 hour, 10 minutes, 40 seconds
How can I calculate the nearest hours to midnight time 00:00 regardless of date in PHP. For example:
If time is 22:00 then 2 hours are required to reach 00:00
If time is 04:00 then -4 hours are the nearest to reach 00:00
Currently I have the following PHP function:
<?php
$ts1 = strtotime('00:00');
$ts2 = strtotime('04:00');
$diff = ($ts1 - $ts2) / 3600;
?>
But this won't be helpful much in the above.
If you have the php Datetime class available you can calculate the difference between two DateTimes.
$time1 = new \DateTime('00:00');
$time2 = new \DateTime('04:00');
$diff = $time1->diff($time2, true);
$hourDifference = 0;
if ($diff->h < 12) {
$hourDifference = -$diff->h;
} elseif ($diff->h > 12) {
$hourDifference = 24 - $diff->h;
} else {
$hourDifference = 12; // kann be positive or negative
}
And you'll get a DateInverall object where you can access, hours, minuts, seconds and compare them with normal php operators.
If you'r not too interested in minutes;
1. Extract minutes.
check if minutes is > or <=30
if greater, 'store' 1
2. Extract hour
check if hour is greater than 12
if not, add 12 (store flag also to say it will be minus)
3. if greater (ref. Step 1), add 1 to extracted hour.
4. 24 - extracted hour is your interval.
Please note, this may be reduced/ simplified greatly.
Your interval (should) be correct to the nearest half hour
The answer depends on the date (not only the time). This is because of daylight saving time changes. For example might 02:59 being closer to 00:00 then 21:01 on the time where daylight saving time will set back hour.
I have to make a notification after 30 days.
foreach ($pdo->query($sql) as $row) {
$date = date_create($row['data']);
$laikotarpas = date_diff(new DateTime("now"), $date);
// var_dump($liko);
$liko = 30 - $laikotarpas->d;
I want correct result in days.
I have added a row at 2014.03.19 and this shows that left 3days to 30.
My goal is to achieve:
I add record at 2014.03.19 and get result how many days have passed from today. I thought that $laikotarpas->d gives a duration in days, but, when i do calculations to set the limit for 30days.
So my main problem is to get correct $liko, but I have no idea how.
I am adding my time using this code (using PDO):
$q->execute(array($name,
date("Y-m-d H:i:s", time())
);
In my database I use DATETIME. And i print that date from SQL using this php:
<?php echo date_format(date_create($data['data']), 'Y-m-d'); ?>
Is my way good? How to improve this?
-----edit-----
I have to use php5.2
Just got an idea, it takes only days and ignores months passed count. How to update that to count duration only in days?
If you want to find the difference between now and a date in the past, try something like this:
PHP >= 5.2.0
$then = '2014-03-19';
$date = new DateTime($then);
$now = new DateTime('now');
$diff = $date->diff($now);
echo $diff->days . ' days since ' . $then . PHP_EOL; // 58 days since 2014-03-19
PHP < 5.2.0
$date = strtotime($then);
$now = time();
$diff = $now - $date;
$days = round($diff / 60 / 60 / 24); // convert seconds to days and round off
Note: after understanding more about your problem, I highly suggest you filter your results based on date ranges in MySQL rather than PHP - it'll be easier and more economic and will reduce your potential risk for affecting data you didn't mean to. See Cull Larson's answer.
You could just use a query like this:
SELECT * FROM myTable WHERE DATE(signupDate) = DATE_SUB(NOW(), INTERVAL 25 DAY);
That will give you all results with a signup date that is 25 days old. If you have a flag in the table telling you whether you've notified them, you can pass that along too:
SELECT * FROM myTable WHERE notified=false AND DATE(signupDate) = DATE_SUB(NOW(), INTERVAL 25 DAY);
If you want to get every record 25 days or older, that hasn't been notified:
SELECT * FROM myTable WHERE notified=false AND DATE(signupDate) <= DATE_SUB(NOW(), INTERVAL 25 DAY);
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
How do i convert the above $interval to seconds in php
Another way to get the number of seconds in an interval is to add it to the zero date, and get the timestamp of that date:
$seconds = date_create('#0')->add($interval)->getTimestamp();
This method will handle intervals created via the DateInterval contructor more or less correctly, whereas shiplu's answer will ignore years, months and days for such intervals. However, shiplu's answer is more accurate for intervals that were created by subtracting two dates. For intervals consisting only of hours, minutes and seconds, both methods will get the correct answer.
There is a function format for this. But it wont return the number of seconds. To get number of seconds you use this technique
$seconds = abs($datetime1->getTimestamp()-$datetime2->getTimestamp());
If you really want to use $interval you need to calculate it.
$seconds = $interval->days*86400 + $interval->h*3600
+ $interval->i*60 + $interval->s;
Here
86400 is the number of seconds in a day
3600 is the number of seconds in an hour
60 is the number of seconds in a minute
I would only add to shiplu's answer:
function dateIntervalToSeconds($interval)
{
$seconds = $interval->days*86400 + $interval->h*3600
+ $interval->i*60 + $interval->s;
return $interval->invert == 1 ? $seconds*(-1) : $seconds;
}
To handle negative intervals.
Note that - contrary to Brilliand's answer - The code above will consider correctly years, months and dates. Because $interval->days is an absolute value ($interval->d is relative to the month).
EDIT: this function is still not correct, as pointed out by #Brilliand. A counter-example is
new DateInterval('P4M3DT2H');
It doesn't handle months well.
i have the flowing code
$LastModified = filemtime($somefile) ;
i want to add ten minute to last modified time and compare with current time then if $LastModified+ 10 minute is equal to current time delete the file . how can i do that ?! i'm little confusing with unix time stamp .
Since the UNIX timestamp is expressed in "seconds since 1970", you just add five minutes in seconds:
$LastModPlusFiveMinutes = $lastModified + (60 * 5);
Or, maybe more readable:
$LastModPlusFiveMinutes = strtotime("+5 minutes", $lastModified);
The unix timestamp is the number of seconds that have passed since Jan 1st, 1970.
Therefore to add 10 minutes you need to add 600 (seconds). To get the current time call time().
e.g.
$LastModified = filemtime($somefile);
if ($LastModified+600 <= time())
{
// delete the file
}
(Note that you said "if $LastModified+ 10 minute is equal to current time delete the file" - I presume you actually meant equal to or less than, otherwise replace <= with == above).
You wrote 5 minutes in the topic and 10 minutes in the context.
Anyway here is the code
$diff = time() - $LastModified ;
if( $diff >= 10 * 60 ){ // don't use ==, you may not find the right second..
//action
}
$LastModified = filemtime($somefile);
$now = time();
if(strtotime($LastModified.'+10 minutes') >= $now){
// delete the file.
}
That should do it.