DateTime difference from two tables - php

I am having 2 table by the name mt_upload and down_time and field are DownTime and DownTime1... i need to caluculate the time difference between 2 field from 2 difference table.can anyone help me out

When using PHP 5.3:
For getting the difference in a useable form so it can be shown to the user fill the data into DateTime objects as in $date1 = new DateTime('2009-11-09 12:13:14'); and then use Datetime::diff() to get a DateInterval object.
Doing this is better than manually calculating the differences as manually handling daylight saving time switches, leap seconds and similar date things can be really hard.

$date1 = '...'; // fetch this from your first table
$date2 = '...'; // fetch this from your second table
// if the dates are NOT unix timestamps use PHP's strtotime() or MySQL's UNIX_TIMESTAMP() to convert them
$difference = abs($date1 - $date2); // difference in second
// divide by 60 for minutes, 3600 for hours, etc etc

In MySql:
select timediff(t2.DownTime,t1.DownTime1)
from mt_upload t1, down_time t2
where t1.id=<some_id> and t2.id=<some_id>;
(of course you need some IDs to select the right records)
This returns you a string in the form HOURS:MINUTES:SECONDS
If you want number of seconds, you can do this:
select hour(timediff(t2.DownTime,t1.DownTime1))*3600
+minute(timediff(t2.DownTime,t1.DownTime1))*60
+second(timediff(t2.DownTime,t1.DownTime1))
from mt_upload t1, down_time t2
where t1.id=<some_id> and t2.id=<some_id>;

Related

Select date stored as Unix Timestamp and compare with given Unix TimeStamp

I am stuck for couple of Days on SQL specific scenario. The scenario is as follows,
I have a table, lets call it traffic which has 2 columns -> date and `vehicle (well many more but those are the two I need to match).
The date column is stored as Unix Timestamp. Now this would have been easy to just compare the current date (obtain from php from time() function) however the trick here is that some of these dates have time attached to them also.
For example if you run strtotime(13-02-2017 13:00) and strtotime(13-02-2017) you will get 2 different results. Basically I only care to match the date and not the time.
So I need some way to select the vehicle and date from the database that are equalled to the current Unix Timestamp but with the trick explained above, so I just need to much the date ONLY if possible.
You can use FROM_UNIXTIME() to convert a timestamp to a datetime, and then use the DATE() function to get the date part of that.
WHERE DATE(FROM_UNIXTIME(date)) = CURDATE()
However, this can't use an index, so another way that can make use of an index is to check if it's in a range of timestamps for the current date:
WHERE date BETWEEN UNIX_TIMESTAMP(CURDATE()) AND UNIX_TIMESTAMP(CURDATE()) + 86399
(there are 86400 seconds in a day).
SELECT * FROM traffic WHERE DATE(date) = DATE(CURRENT_TIMESTAMP);

SQL - Time since date

I am struggling with one thing. I'm trying to calculate how many days ago a certain date was, by using SQL. The dates I have in my database can be in two formats:
Aug 28 2014, 17:17:34 CEST
Dec 29 2015, 01:03:14 CET
Those are two examples of different dates. Notice the "CET" and "CEST".
But anyways, how would I go ahead and calculate this in a SQL query? I managed to do this in PHP but I'd like to do this in the SQL query itself (if possible). Because it would save up on a lot of memory usage. I try make my work as fast as possible. I want to only access data from users that has only logged in the past 2-3 days or so. Of course I could make a SELECT * FROM users and then run PHP to check for the dates. But is there perhaps a way to do this in SQL? Like: SELECT * FROM users WHERE [lastlogin < 2 days]
Here is my current PHP code. I'd really want to do this in SQL. By the way, my columns are currently in text. Datetime does not work with that format for some reason.
$lastlogin = $row['lastlogin'];
$lastlogin = str_replace("\xc2\xa0",' ',$lastlogin);
$Date = $lastlogin;
$Date = substr($Date, 0, strpos($Date, " CE"));
$now = date('Y-m-d');
$datetime1 = new DateTime($Date);
$datetime2 = new DateTime($now);
$interval = $datetime1->diff($datetime2);
$difference = $interval->format('%a days ago');
echo "Last login was: " . $difference;
you should alter your table to clean up the data. convert the data to two columns with the timezone info in one column and the date and time in another column.
you can split the data easily using SUBSTRING_INDEX() and convert the string to datetime at the same time.
split on the "C" of "CET" and "CEST" like this:
SELECT SUBSTRING_INDEX("Aug 28 2014, 17:17:34 CEST","C",1)
and you will see you are left with the date and time part only, albeit still in a string format. That can be changed with STR_TO_DATE and you can do both on the fly.
First add the new columns to store the data:
ALTER yourtablename ADD newdatecolumn DATETIME AFTER oldcolumnname;
ALTER yourtablename ADD newtimezonecolumn VARCHAR(4) AFTER newdatecolumn;
UPDATE yourtablename
SET newdatecolumn =
STR_TO_DATE(SUBSTRING_INDEX(olddatecolumn,"C",1), '%b %d %Y, %T')
you can then use SUBSTRING_INEX again, this time splitting on the last space in the column and grabbing the timezone for the other new column
UPDATE yourtablename
SET newtimezonecolumn = SUBSTRING_INDEX(olddatecolumn," ",-1)
then you will have data that you can work with more easily to use the suggested DATEDIFF() or other time and date functions. You can drop your old date column if you need to.
Note that yourtablename etc should be changed for actual table and column names.
You can use to_days() or datediff() functions
http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html

How to compare two DATETIMEs from MySQL

I want to limit my users to only (be able to) post something every 15 minutes.
So in my SQL query I select NOW() to get the current date and time, and also the user's last post date date_added. I want to compare the two dates and if the difference between now() and date_added is less than 15 minutes, then the user cannot yet post. If it's greater then he can. If less than 15 minutes then I'd like a message like 'Please wait x minutes and y seconds.' So I need some kind of date manipulation/comparison.
How should I approach this. In MySQL or PHP?
You could simply convert the mysql timestamp into a php-date and compare from there
$time = date ("Y-m-d H:i:s", $mysqltime);
You will find lots of useful snippets how to compare dates on the functions documentation: http://php.net/manual/de/function.date.php
Edit: pozs anwser nails it ...
In MySQL: DATE_ADD() or DATE_SUB(), then compare.
In PHP: DateTime->diff().
Something like
SELECT count(*) FROM posts WHERE last_post > DATE_SUB(NOW(), INTERVAL 15 minute);

php sql date time comparison

I have a last_notified column on my MySQL table, data type DATETIME
I want to either only select the rows where last_notified is more than n seconds old, or compare the last_notified value from the db in php.
I have tried messing around with the date object.
$d = date('Y-m-d H:i:s'); // current date and time
$dd = date('2011-09-08 10:21:34'); // this is the format used in mysql.
I know I cannot just compare them, and i'm unaware of how to add time to the date object. I have seen examples of people using something along the lines of
$t = explode(" ",$dd);
date($dd, strtotime('+30 minutes', strtotime($t[1])));
but that doesn't work . I'm just not seeing it.
You can use sql like this:
SELECT * FROM your_table WHERE last_notified < DATE_SUB(NOW(), INTERVAL n SECOND)
Take a look at your first snippet and date mask in first line
Y-m-d H:m:s
you use m mask twice, so it means there will be month instead of minutes.
you should use i mask to specify the minutes
SELECT * FROM your_table WHERE last_notified < DATE_SUB(NOW(), INTERVAL n SECOND)

PHP - Comparing time

I'm working on a calendar/planner web app and I need to compare the start and end times of events before I store them in my DB. An event can only have a range of one day and between 8am and midnight. The start time always has to take place before the end time.
The post values come from the form in the following format hh:mm:ss (12:14:00) etc.. so I can store them in my database without much hassle. Is there any way I can compare these times?
Thanks a lot!
If those times are in the database, comparison operator of the database would works. For example:
SELECT * FROM table WHERE time < NOW()
In PHP, the easiest way to compare times is to convert them to timestamps, and then to compare timestamps as integers. You can use strtotime to do that conversion.
For example:
$time1 = "08:00:00";
$time2 = "09:00:00";
if (strtotime($time1) > strtotime($time2) ||
strtotime($time1) < strtotime("08:00:00")) {
...
}
If you're running PHP 5.3, you can use the diff() method of DateTime objects to get the difference in between two dates. But it's possible to do with just timestamps too (1 day = 86400 seconds)

Categories