Find TimeDiff between two dates - php

I have a MySQL database with some columns and in two of them I have two different dates.
In the site I have the two dates in a two colums inside a table, but I need to calculate and reproduce in another column the number of days between that two dates.
I found this code:
?php
$date1 = date_create("2017-04-15");
$date2 = date_create("2017-05-18");
//difference between two dates
$diff = date_diff($date1,$date2);
//count days
echo 'Days Count - '.$diff->format("%a");
?
And it works but I need to change this dates and put the data inside my database. Jow can I solve this?
Im using this:
update client_invoices
set x6 = datediff(x4, date_due)
as an event in mysql but everytime they updates the server the "Event scheduler status" is turned off.
How can i perform this directly in my sql without scheduling events?
Thanks,
Ribas

In MySQL, you would simply use datediff():
select t.*, datediff(day1, day2) as days_diff
from t;
If you want to update a column:
update t
set diff = datediff(day1, day2);

Related

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

Using MySQL, PHP and cron to sum daily values based on timestamped data

I am trying to piece together a bunch of steps and it is getting confusing.
I have a MySQL table with (MySQL) timestamp and runtime fields. I would like to make another table containing date and sum (runtime) fields.
I would like to execute a cron job every day after midnight to sum the runtimes from the day before and insert that with the date of the previous day.
I would like the cron job to make sure that the prior days were run, and if not, it would run those as well.
I am new to cron, so I don't know if that last step is necessary.
Here are my trouble points:
Writing a query that will convert timestamps to dates and sum each date.
Setting up a PHP cron job that will make sure all dates are entered but not double enter.
Here's the code I've tried on part 1 (I'm running on CURDATE until it works):
$result=mysql_query("SELECT SUM(runtime) AS value_today FROM `table` WHERE date = CURDATE()",$link)
$row = mysql_fetch_array($result);
echo $row[value_today];
instead of convert timestamp from query, why dont just set a variable using php by
$yesterday_date = date('Y-m-d', strtotime('-1 days'))
to get yesterday date
then query
SELECT SUM(runtime) AS total FROM db_table WHERE DATE(date_run) = '" . $yesterday_date . "' GROUP BY DATE(date_run)"

mysql - select last two tables based on their date of creation

I need some advise on implementing my database schema properly. I have a cron script whose main functions are to Parse HTML docs => Create a DB tbl => Insert Records
I am used to run this script only once per month but I need to do it more frequently which means my database tables will increase significantly. At the moment my tables follow this format : table_03 where the last two digits represent the current month.
Now I am considering using PHP time() function to replace the current month.
My first question, is this a good way to approach it ?
My second issue is how do you go about creating a dynamic SELECT statement that fetches the last two tables in a Database based on their date ? or could be better to know if there is an MySQL query that does this job instead of relying of the table names ?
e.g
table_29_03 // 29 March
table_26_03 // 26 Mar...
table_25_03
...
My query should return the difference between the last two or three table, but not having consistent dates ( as monthly ) I am not sure how to do it.
At the moment I am doing the following :
$thisMonth = 'table_'.date('m');
$PrevMonth = 'table_'.date('m', strtotime('first day of last month'));
// find new records in this table not available in previous one
$sql = "
SELECT * FROM `".$thisMonth."` WHERE `".$thisMonth."`.`id`
NOT IN (
SELECT `".$PrevMonth."`.`id`
FROM `".$PrevMonth."`
WHERE `".$thisMonth."`.`id` = `".$PrevMonth."`.`id`
); ";
My second issue is how do you go about creating a dynamic SELECT statement that fetches the last two tables in a Database based on their date ?
is this what you want to achieve in MySQL?
SELECT create_time,table_name
FROM INFORMATION_SCHEMA.TABLES
ORDER BY create_time DESC LIMIT 2
you can add additional filters like what schema should we extract the data from, etc...
As for your first question, I am using gmdate as of now to extract the month and year of time.
$now = time();
$month = gmdate("m", $now);
$year = gmdate("y", $now);
gmdate: time returned is in Greenwich Mean Time (GMT).
using time(); to set your month is alright and i can see no problem in that.
Side Note: If you are running PHP and MySQL on separate machines, there would be some discrepancies in time if the datetime of those two are not synced. if you want an accurate time representation of both. You should be dependent on one machine.
If you want PHP to handle time logging, you can include a column in in your tables like 'created_at' which indicates the time when it was generated, based on PHP time();
If you want MySQL to handle it, you can query first the current date
select curdate();
then create the table names based on the month you fetched from your query.

How to update/Insert random dates in SQL within a specified Date Range

Please forgive me. I am an absolute newbie and I need help with this table in phpmyadmin
My Table has the following columns:
Primary_ID, Begin_Date, End_Date, Timestamp
How do I update in phpmyadmin, selected rows with randomly generated begin_dates and timestamp within a specified date range (eg: 30 days in a month).
E.g of desired outcome
Primary_id--- Begin_Date -------------Timestamp
1.------------2008-09-02--------------2008-09-02 21:48:09
2.------------2008-09-03--------------2008-09-03 15:19:01
3.------------2008-09-14--------------2008-09-14 01:23:12
4.------------2008-09-27--------------2008-09-27 19:03:59
Date Range between 2008-09-01 and 2008-09-31.
Time is variable 24 hrs
I am a newbie, so a syntax that will work in phpmyadmin will help greatly.
We are making a presentation for a gym site with 500 members but the added member values all have the same begin date and time. Trying to separate them into different monthly registrations in the database, eg 50 people registered in August at different days and times, 35 people in October, etc. Hope it is clearer now. Thanks –
When I try one of the below answers, I get this error: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '$randomDate = rand(1,31)' at line 1. So ideally, a code I can copy and paste into phpmyadmin with minimal editing will be appreciated. In sequence if possible. For a total dummy to understand and execute.
I'd start with something like this. A bunch of these can be combined, but I split it up so you can see what I'm doing.
To get random numbers, you can use rand(). Get one for the date, hour, minute, and second
$randomDate = rand(1,31);
$randomHour = rand(1,24);
$randomMinute = rand(0,59);
$randomSecond = rand(0,59);
You will want leading zeros (03 instead of 3) so you can use str_pad to add them, if required
$randomDate = str_pad($randomDate, 2, '0',STR_PAD_LEFT);
//The '2' is how many characters you want total
//The '0' is what will be added to the left if the value is short a character
Do the same with all your other random values.
Just because I like neat queries, you should make up your final update strings next.
$newDate = '2008-09-'.$randomDate;
$newTime = $randomHour.':'.$randomMinute.':'.$randomSecond;
Now I don't know how you're determining which rows you want to update, so I will leave that up to you. For an example, I will show you a query if you wanted to do this with Primary_id 3:
$x = mysql_query("UPDATE yourTable SET Begin_Date=\"$newDate\", Timestamp=\"$newTime\" WHERE Primary_id = 3");
something like:
insert into myTable (begin_date) values date_add('2008-09-01', INTERVAL RAND()*30 DAY)
that should create a new row with a random begin_date
update myTable set Timestamp = date_add(begin_date, INTERVAL RAND()*1440 MINUTE)
then that one should set the timestamp to a random minute of that day.

DateTime difference from two tables

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>;

Categories