Calculate difference between two datetimes - php

I am using PHP and MySQL, and want to calculate date time difference between two datetimes. I have a message table, in that table createdate is one field. I want to find out day and time difference from current date in the format 1 day 2 hours ago. What is the best way to go about this?

Use PHP's built in date functions:
<?php
$start_time = "Y-m-d H:i:s"; // fill this in with actual time in this format
$end_time = "Y-m-d H:i:s"; // fill this in with actual time in this format
// both of the above formats are the same as what MySQL stores its
// DATETIMEs in
$start = new DateTime($start_time);
$interval = $start->diff(new DateTime($end_time));
echo $interval->format("d \d\a\y\s h \h\o\u\r\s");
DateInterval documentation
DateTime::diff documentation

SELECT TIMESTAMPDIFF(HOUR,createdate,NOW()) as diff_in_hours FROM table1;
Then on php side you can easily convert the value of diff_in_hours to days + hours format.

You can use DATEDIFF() and TIMEDIFF() functions in MySQL.
SELECT DATEDIFF(CURDATE(), createdate) AS output_day,
TIMEDIFF(CURDATE(), createdate) AS output_time
FROM message_table
For output_day it is already in day unit. But output_time require additional manipulation to get the hour part of the time difference.
Hope this helps.

Related

Calculate total subscription end date from multiple subscription end dates in PHP

Today is 2014-11-16.
I got these three dates in the future but I want them to be only one date instead.
2014-12-15 21:27:12
2014-12-15 21:32:20
2014-12-16 12:22:09
I want to get the total end date from today. That would be aproximately three month into the future but how can i calculate it to be the same date each time from the three dates above?
How can this be achieved with PHP's DateTime and DateInterval classes?
This might help:
$dateTimeObject=new DateTime(date('Y-m-d h:i:s', strtotime('2014-12-16 12:22:09')));
//to get diff with now
$diff = $dateTimeObject->diff(new DateTime(date('Y-m-d h:i:s')));
Then,
//to get diff months
echo $diff->m;
//to get diff hours
echo $diff->h;
//to get diff minutes
echo $diff->i;
And so on.
It is highly recommended to take a look at the PHP's DateTime official document.
Note that, DateTime is available on PHP >=5.2.0

Calculating the date weeks using the date() function

I have a website which saves images into a database. I have successfully made a function that calculates the date that an image is added and this value is also saved into the database. I now want to calculate the date two weeks ahead from the addition date. This will show the date that the image file will cease to exist in the database.
I used the function:
$dateofaddedimage= date("d/m/Y");
This calculate thee current date of the addition of the image.
I am aware that there is the strtodate() function, but i don't think it will help.
Does anyone know how to add two weeks onto this function?
Thanks!
Add a number to time(), which is the current time stamp as seconds from the Unix Epoch.
$twoweeks = time() + (2*7*24*60*60);
$thatasdate = date("d/m/Y", $twoweeks) ;
Check out date_add and the PHP DateTime model.
From the php manual page comes this fine example:
<?php
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('P10D'));
echo $date->format('Y-m-d') . "\n";
If you use this on your problem, you'd have
<?php
$dateofaddedimage = new DateTime('now'); //creates DateTime Model of today (and now)
$dateofimagedestroy = new DateTime('now'); //creates DateTime Model of today as well
$dateofimagedestroy->add(new DateInterval('P14D')); // adds 14 Days to the second date
The problem with what you are doing is that date() returns a string formatted to the date - not a proper date.
I would suggest either inserting a datetime into the database such as:
insert into yourTable (timeColumn) values (now());
This will insert the actual date. From there you can use mysql functions to add and subtract from this date.
Or using a timestamp in your code such as:
$uploadedTime=time();
From there you can either use PHP functions to add or subtract dates, or (as it is a timestamp) you can also use mysql functions to calculate what you need inside queries themselves.

Compare timestamp to date

I need to compare a timestamp to a date. I would just like to compare the date portion without the time bit. I need to check whether a timestamp occurs on the day before yesterday i.e. today - 2.
Could you show me a snippet please? Thank you.
I've been reading through the PHP docs but couldn't find a very clean way of doing this. What I found was converting the timestamp to a date with a particular format and comparing it to a date which I get by doing a time delta to get the date before yesterday and converting it to a particular format. Messy.
You can arcieve this by using the function strtotime.
To round to a day I personaly like to edit the timestamp. This is a notations of seconds since epoch. One day is 86400 seconds, so if you do the following caculation:
$time = $time - ( $time % 86400 );
You can convert it back to a date again with the date function of PHP, for example:
$readableFormat = date( 'd-m-Y', $time );
There is also much on the internet about this topic.
you can use the strtotime function
<?php
$time = strtotime("5 june 2010");
$before = strtotime("-1 day",$time);
$after = strtotime("+1 day",$time);

how to subtract two dates and times to get difference

i have to sent an email when a user register email contain a link that is become invalid after six hours
what i m doing when email is sent i update the db with field emailSentDate of type "datetime"
now i got the curent date and time and has made to the same formate as it is in db now i want to find that both these dates and time have differenc of 6 hours or not so that i can make link invalid but i donot know how to do this
my code is look like this i m using hardcoded value for db just for example
$current_date_time=date("Y-m-d h:i:s");
$current=explode(" ",$current_date_time);
$current_date=$current[0];
$current_time=$current[1];
$db_date_time="2010-07-30 13:11:50";
$db=explode(" ",$db_date_time);
$db_date=$db[0];
$db_time=$db[1];
i do not know how to proceed plz help
<?php
//$now = new DateTime(); // current date/time
$now = new DateTime("2010-07-28 01:11:50");
$ref = new DateTime("2010-07-30 05:56:40");
$diff = $now->diff($ref);
printf('%d days, %d hours, %d minutes', $diff->d, $diff->h, $diff->i);
prints 2 days, 4 hours, 44 minutes
see http://docs.php.net/datetime.diff
edit: But you could also shift the problem more to the database side, e.g. by storing the expiration date/time in the table and then do a query like
... WHERE key='7gedufgweufg' AND expires<Now()
Many rdbms have reasonable/good support for date/time arithmetic.
What you can do is convert both of your dates to Unix epoch times, that is, the equivalent number of seconds since midnight on the 31st of December 1969. From that you can easily deduce the amount of time elapsed between the two dates. To do this you can either use mktime() or strtotime()
All the best.
$hoursDiff = ( time() - strtotime("2010-07-30 13:11:50") )/(60 * 60);
I'd rather work with a timestamp: Save the value which is returned by "time()" as "savedTime" to your database (that's a timestamp in seconds). Subtract that number from "time()" when you check for your six hours.
if ((time() - savedTime) > 6 * 3600)
// more than 6h ago
or
"SELECT FROM table WHERE savedTime < " . (time() - 6 * 3600)
This might be the solution to your problem -> How to calculate the difference between two dates using PHP?

Converting TIMESTAMP to unix time in PHP?

Currently I store the time in my database like so: 2010-05-17 19:13:37
However, I need to compare two times, and I feel it would be easier to do if it were a unix timestamp such as 1274119041. (These two times are different)
So how could I convert the timestamp to unix timestamp? Is there a simple php function for it?
You're looking for strtotime()
You want strtotime:
print strtotime('2010-05-17 19:13:37'); // => 1274123617
Getting a unixtimestamp:
$unixTimestamp = time();
Converting to mysql datetime format:
$mysqlTimestamp = date("Y-m-d H:i:s", $unixTimestamp);
Getting some mysql timestamp:
$mysqlTimestamp = '2013-01-10 12:13:37';
Converting it to a unixtimestamp:
$unixTimestamp = strtotime('2010-05-17 19:13:37');
...comparing it with one or a range of times, to see if the user entered a realistic time:
if($unixTimestamp > strtotime("1999-12-15") && $unixTimestamp < strtotime("2025-12-15"))
{...}
Unix timestamps are safer too. You can do the following to check if a url passed variable is valid, before checking (for example) the previous range check:
if(ctype_digit($_GET["UpdateTimestamp"]))
{...}
If you're using MySQL as your database, it can return date fields as unix timestamps with UNIX_TIMESTAMP:
SELECT UNIX_TIMESTAMP(my_datetime_field)
You can also do it on the PHP side with strtotime:
strtotime('2010-05-17 19:13:37');
if you store the time in the database, why don't you let the database also give you the unix timestamp of it? see UNIX_TIMESTAMP(date), eg.
SELECT UNIX_TIMESTAMP(date) ...;
databases can also do date and time comparisons and arithmetic.

Categories