PHP| arrays with times - php

I need to compare bentween a time taken from a database to the current time.
$DBtime = "2013-10-29 17:38:55";
this is the format of the arrays in the database.
How can I compare it with the current time?
Im not sure how, but maybe converting DBtime to Unixtime then:
(CurrentUnixTime - dbUnixTime) = x
Or maybe, we can take the 17:38 and compare it somehow with date("G:i");
Thank you! I hope you understand what I mean.

You can transform it into a UNIX timestamp using strtotime and then subtract the current timestamp by it.
$DBtime = "2013-10-29 17:38:55";
$db_timestamp = strtotime($DBtime);
$now = time();
$difference = $now - $db_timestamp;
echo $difference;
This will give you the difference in seconds.

You can convert the DBtime string to a unix timestamp in PHP using strtotime. In MySQL, you can use UNIX_TIMESTAMP when querying the column.
time() - strtotime($DBtime)

$date1 = new DateTime('2013-10-29 17:38:55');
$date2 = new DateTime('2013-11-29 18:28:21');
$diff = $date1->diff($date2);
echo $diff->format('%m month, %d days, %h hours, %i minutes');

$DBtime = "2013-10-29 17:38:55";
// Set whatever timezone was used to save the data originally
date_default_timezone_set('CST6CDT');
// Get the current date/time and format the same as your input date
$curdate=date("Y-m-d H:i:s", time());
if($DBtime == $curdate) {
// They match, do something
} else {
// They don't match
}

Related

PHP - Difference between two times

I've created a timing system for a charity race. I'm trying to find the difference between the start time and the finishers time using PHP. I'm not sure I'm recording the times correctly, but this is the start time i just recorded...
20180808180653
And this is a finisher time...
20180808180654
The difference between them is roughly 1 hour 24, but when i use...
date('h:i:s', $finshTime-$startTime)
I get 03:24:20 not 01:34:20.
Can someone please help?
The date method accepts as "integer Unix timestamp". You are supplying instead a number of seconds (1 in your example).
$start = '20180808180653';
$end = '20180808180654';
$diff = $end - $start;
var_dump($diff); //1
$d = date('h:i:s', $$diff);
var_dump($d); //04:00:01
//the above is wrong. You need to try something like the code below
$dStart = new DateTime($start);
$dEnd = new DateTime($end);
$interval = $dStart->diff($dEnd);
var_dump($interval->format('%h:%i:%s'));
I'd be leery using a string representation of a datetime that looks like that. Convert the whole thing into a date format that makes sense like yyyy-mm-dd hh:mm:ss, or a valid unix time stamp.
Your first approach isn't that far off, you just need to use a strtotime function. I'd guarantee that you can first make an accurate Date or Unix time representation of those strings you are using. Rest should fall into place.
First check if the type of $finshTime and $startTime are integer.
you can use get variable type:
gettype($startTime);
if this is the case try this with ():
$diff_date = date('h:i:s', ($finshTime - $startTime) );
if $startTime and $finshTime are string try this:
$diff_date = date('h:i:s', (strtotime($finshTime) - strtotime($startTime)) );

Having a hard time understanding how to manipulate date and time in PHP

I'm really not grasping how dates and times get formatted in PHP for use in mathematical equations. My goal is this;
Get a date and time from the database;
// Get array for times in
$sth = mysqli_query($conn,"SELECT * FROM ledger ORDER BY ID");
$timeins = array();
while($r = mysqli_fetch_assoc($sth)) {
$timeins[] = $r["timein"];
//OR
array_push($timeins, $r['timein']);
}
And then find the distance between the current time and the variable in the array, $timeins[0], and then put the minutes, hours, and days difference in separate simple variables for later use. These variables will be used on their own in if statements to find out if the person has passed certain amounts of time.
edit: the format of the dates being returned from the DB is in the default TIMESTAMP format for MySQL. E.g. 2018-08-06 17:38:37.
It is also possible to perform datetime operations in SQL, to get a difference between two datetime/timestamp values in days, hours, minutes... We can use expressions in the SELECT list, to return the results as columns in the resultset.
Ditching the SELECT * pattern, and specifying an explicit list of expressions that we need returned:
$sql = "
SELECT t.id
, t.timein
, TIMESTAMPDIFF(DAY ,t.timein,NOW()) AS diff_days
, TIMESTAMPDIFF(HOUR ,t.timein,NOW()) AS diff_hours
, TIMESTAMPDIFF(MINUTE ,t.timein,NOW()) AS diff_minute
FROM ledger t
ORDER BY t.id ";
if( $sth = mysqli_query($conn,$sql) ) {
// execution successful
...
} else {
// handle sql error
}
You should use the DateTime class in PHP to do any date manipulation. You can convert a string representation of a MySQL format time to a PHP DateTime object using
$date = DateTime::createFromFormat('Y-m-d H:i:s', $mysqldate);
Also you can create a DateTime object representing the current time using the constructor with no argument:
$now = new DateTime();
To get the difference between two dates as a DateInterval object, use the builtin diff method:
$diff = $now->diff($date);
As a complete example:
$now = new DateTime();
$mysqldate = '2018-04-03 12:30:01';
$date = DateTime::createFromFormat('Y-m-d H:i:s', $mysqldate);
$diff = $now->diff($date);
$diff_days = (int)$diff->format('%a');
$diff_hours = $diff->h;
$diff_minutes = $diff->m;
echo "$diff_days days, $diff_hours hours, $diff_minutes minutes";
Output:
125 days, 9 hours, 4 minutes
Note that you have to use $diff->format('%a') rather than $diff->d to get the days between two dates, as $diff->d will not include the days in any months between the two dates (in this example it will return 3 for today being August 6).
Using the DateTime Class in php is the best way to get accurate results.
$dateNow = new DateTime('now');
$dateIn = DateTime::createFromFormat('d-m-Y H:i:s', $timeins[0]);
$interval = $dateNow->diff($dateIn);
echo $interval->format('%d days, %h hours, %i minutes, %s seconds');
$deltaDays = $interval->d;
$deltaHours = $interval->h;
...
You have to make sure the input format for you DB date is correct, in this case, I assumed d-m-y H:i:s, and then you can output in any format you need as well, as shown in the date docs: http://php.net/manual/en/function.date.php

How to compare current time with old time in PHP

I have stored date field at DB.
In PHP, i am getting that field and converted into date.
I want to compare that time with current time. If that difference is above 60 minutes. It will return some value.
I dont know how to write logic for that
$lastUpdatedField = $rows_fetch['lastUpdatedTime'];
$lastUpdatedDate = new DateTime($lastUpdatedField);
$nowDate = new DateTime(date('y-m-d h:m:s'));
I have old date&time is in $lastUpdatedDate variable, and current time is in $nowDate.
How to compare these two
$interval = $nowDate->diff($lastUpdatedDate);
echo $interval->h;
DateDiff: http://www.php.net/manual/en/datetime.diff.php
DateInterval: http://www.php.net/manual/en/class.dateinterval.php
Had The same problem earlier its actually quit simple
heres the piece where you declare your variables
$lastUpdateddate = new DateTime($lastUpdatedField);
$nowDate = new DateTime(date('y-m-d h:m:s'));
Then you have to convert them to second - format so that you can do math with them
To do that use strtotime
$Diff = strtotime($lastUpdatedDate) - strtotime($nowDate);
Then just check to see if the difference in time is more then 60 minutes,
So devide by 60 seconds to get minutes and by 60 to get hours
if ($diff/60/60 <= 1){
//do your thing here
{
First convert the current time and old time to one unit like Unix timestamp passing it through strtotime(). Then differentiate both the timestamp to get the difference between two times.
$difftime = strtotime(date('Y-m-d H:i:s')) - strtotime($rows_fetch['lastUpdatedTime']);
Then convert the difference to days as follows :
$days=$difftime/24*60*60;
Once you get the days you can get the minutes from it as below to compare to meet your need.
$timediff = $days * 24 * 60;

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
}

Check interval between datetimes in PHP

I have a field in database that has type of datetime in which I add time when user visit a page. When user again comes I want to check the interval between his first visit and current. If it is less or equal to 1 hour then I want to show him some message.
I store time like this
2011-03-04 00:25:01
The thing that I want to ask that how to check the interval in PHP
You could try
SELECT COUNT(#UserID) FROM table WHERE LastVisit > (DateADD(now(),interval -1 Hour))
you can then check the count
Edit: added FROM clause
If you have PHP >= 5.3 you can use DateTime objects and functions:
$visit = DateTime::createFromFormat('Y-m-d H:i:s', '2011-03-04 00:25:01');
$now = new DateTime("now");
$diff = $now->diff($visit);
What you can so is, retrieve the the datetime, store it in a variable.
Create a var with time().
You can then convert the db datetime to a timestring using strtotime()
Subtract the datetime timestring from the new time. That should give you a difference in seconds. You can then manipulate your values and do the relevant checks.
$db = datetime_from_database;
$now = time();
$last = strtotime($db);
$diff = $now - $last; //this is in seconds
You can do something like
$minutes = $diff / 60;
If ($minutes > 60) echo 'more than 1 hour; 60 minutes';
Just work in it.
You can then use the date functions to format the new datetime using the $now and update the database.

Categories