SQL/PHP Compare two dates as seconds - php

I have a field called lastTime which holds the current time when I make a query to my table using NOW().
It's stored as datetime in my table.
I then retrieve this value at some point from the table with a query and it returns a string.
$lastTime = retrieve_lasttime_from_table();
$curTime = date("Y-m-d H:i:s");
if($curTime - $lastTime >= 5){
//Do stuff here
}
So basically I'm trying to see if 5 seconds have passed.
What's the correct way to do this?

strtotime() is the best way to find the difference
if((strtotime($curTime) - strtotime($lastTime)) >= 5){
//Do stuff here
}

You can use strtotime and below example would probably work.
if(strtotime($lastTime) - (strtotime($curTime)) >= 5){
if((strtotime($curTime) - strtotime($lastTime)) >= 5){
//Do stuff here
}
Note: I switched the positions of $lastTime and $curTime, as I guess you need to check, when Current Time is greater than or equal to 5 seconds from Last time.

Related

In php check if an item is between a given date range

I'm suck on the logic for this, my goal is to execute if an item is with in a given date range.
I get yesterday's date and the date from 8 days ago with Carbon like so:
$dt = \Carbon\Carbon::yesterday();
$dtB = \Carbon\Carbon::yesterday()->subDays(8);
$today = $dt->toDateString();
$todayBack = $dtB->toDateString();
I then need to execute this if statement to find if the item in the database fits with in these time frames.
if($orderSet->item_clicked == 'printing' && $orderSet->completed_date == $today) {
// run some stuff here
}
Currently I can execute if it's today but I would like do in between these two days. In example. 09-20-19 - 10-09-19 in between these two dates. Just as an example.
Carbon has a between() method. Use the original carbonized dates instead of the date strings.
$dtCompleted = \Carbon\Carbon::parse($orderSet->completed_date);
if (if($orderSet->item_clicked == 'printing' && $dtCompleted->between($dtB, $dt)) {
// run some stuff
}
See the documentation of Comparison

Deducting 24 hours from a timestamp

I am wondering if there is an easy way to do this, i'm pulling a timestamp from mysql, i then want to check if the timestamp is less than 24 hours ago, if it is, i do nothing, else i will do an action, my code:
$dbStoredDate = $theDate['site_date'];
$theTimeMinus = strtotime('-1 day', $dbStoredDate);
if ($theTimeMinus <= $dbStoredDate) {
}
This is what i have come up with, i realize now it would have been better if i used time() instead of timestamp() in mysql, lesson learned, the first value is coming from mysql, the second is just deducting 1 day, does the logic look ok do you think? thanks for any input guys.
You can do this easily (assuming you're using unix timestamp, if not you can convert it):
$continue = ((time() >= ($theDate['site_date']+86400));
if ($continue)
echo "older than/equal to 24 hours";
else
echo "not older than 24 hours";

PHP MYSQL compare time with created in database

I want to check if 30 min passed after created time in database. created is a time column having time stamp in this format 1374766406
I have tried to check with date('m-d-y H:i, $created) but than of course it is giving human readable output so don't know how to perform check if current time is not reached to 30min of created time.
Something like if(created > 30){}
Try this:
$created = // get value of column by mysql and save it here.
if ($created >= strtotime("-30 minutes")) {
// its over 30 minutes old
}
The better approach is to use DateTime for (PHP 5 >= 5.3.0)
$datenow = new DateTime();
$datenow->getTimestamp();
$datedb = new DateTime();
$datedb->setTimestamp(1374766406);
$interval = $datenow->diff($datedb);
$minutes = $interval->format('%i');
$minutes will give you the difference in minutes, check here for more
http://in3.php.net/manual/en/datetime.diff.php
Here is the working code
http://phpfiddle.org/main/code/jxv-eyg
You need to use strtotime(); to convert the date in human form back to a timestamp, then you can compare.
EDIT: Maybe I misread.
So something like;
if(($epoch_from_db - time()) >= 1800){
//do something
}

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

add two time values and comparing with other time

i have two time values say starttime=23:00:00 and estimation time=00:45:00 now i want to add starttime and estimation time and store it in a variable i did like this
$add = abs(strtotime($starttime) + strtotime($estimationtime));
and now i have to compare a new time say currenttime or any other time interval (23:50:00)
if($time >=$starttime && $time <=$add)
{
$message=array("message"=>"there is an appointment");
}
if i echo $add i am not getting the right format it shows 2675756700 pls help me to solve this
If you want to echo your $add variable in a readable form you have to format it first.
echo(date("H:i:s", $add));
strtotime() returns a timestamp, which is the number of seconds since Jan 1/1970. You cannot compare this to a formatted time value - it's just an integer.
So basically, you're doing the equivalent of:
$add = 1 + 2; // 3
if (3 >= '23:50:00') ...
if you want to compare time values as timestamps, you'll have to convert EVERYTHING to timestamps. Or, you could use the DateTime object, which'll handle a lot of this sort of thing for you automatically.

Categories