PHP Date - Time difference formatting - php

I have a date and time saved in a database, in the following format: 2016-04-03 12:54:11
Basically, this date and timestamp represents the exact date and time something was created. What I'm trying to do is display a second date and time, that is the exact number of days since the first timestamp.
So if the timestamp in the dataase was 2016-04-03 12:54:11 and todays date and time is 2016-04-04 12:54:11, it would display: Overdue by: 1 Day
So far I have:
<?PHP $dateCreated = mysql_result(mysql_query("SQL to stored date and time"),0);
$dateNow = time();
$dateDifference = abs(strtotime($dateCreated) - strtotime($dateNow));
$years = floor($dateDifference / (365*60*60*24));
$months = floor(($dateDifference - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($dateDifference - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24)); ?>
And then:
echo "<strong>Overdue by:</strong> $days Days.";
however, this code displays that 2 dates, only a day apart, as 14 days apart.
Help would be appreciated, cheers.

Try using DateTime objects. They'll make your life much easier.
The above could then be achieved with the following:
$date1 = new DateTime('2016-04-03 12:54:11');
$date2 = new DateTime('2016-04-04 12:54:11');
$diff = $date1->diff($date2);
The $diff variable will then be a DateInterval object, which has a days property to show the amount of days between the two dates. In this case 1, so you can do:
echo "Overdue by: " . $diff->days . " days.";
Which will output Overdue by: 1 days..
On a side-note: You should really not be using mysql_ functions anymore. They have been deprecated for years and are no longer part of the PHP core in the latest PHP version. So this code will not work on an up-to-date server. Also see: Why shouldn't I use mysql_* functions in PHP?

I think the best way to do it is using the Php DateTime class witch allow us to do it.
Try this:
$datetime1 = new DateTime("YOUR_DB_TIMESTAMP");
$datetime2 = new DateTime("today");
$difference = $datetime1->diff($datetime2);
echo difference->d;
Also, you can choose the way that you want to show the diference.
$diff->format('%R%a days')
Reference:
Example-> Finding the number of days between two dates
DateTime Doc -> http://php.net/manual/es/class.datetime.php
Regards!

I would use the DateTime object for things like this, because are really a very big help.
$dateCreatedObj = DateTime::createFromFormat('Y-m-d H:i:s', $dateCreated);
$dateNowObj = new DateTime();
$dateDifference = $dateCreatedObj->diff($dateNowObj);
echo $dateDifference->format('Overdue by: %a Day');
Please note that this does not handle timezones, multilingual and plural issues.

Diff function returns the difference between two DateTimeInterface objects.
You can try to use DateTime object :
<?PHP $dateCreated = mysql_result(mysql_query("SQL to stored date and time"),0);
$dateNow = new DateTime();
$dateOther = new DateTime($dateCreated);
$interval = $dateNow->diff($dateOther);
echo $interval->format('%R%a days');

Related

Calculating MySQL and PHP date difference in days

I am trying to calculate a date difference in days using MySQL and PHP date.
My code
$ArrivalDate = $variants_data['ArrivalDate'];
$daydiff=floor((abs(strtotime(date("d/m/Y")) - strtotime($ArrivalDate))/(60*60*24)));
Output
<td>'.$daydiff.'</td>
Results
I get 93 days instead of 26 days (got 26 days using this calculator http://easycalculation.com/date-day/number-of-days.php)
ArrivalDate value = 2013-05-03 from MySQL table and it changes due to transport delays, etc.
How can I achieve this in PHP?
try this
$daydiff=floor((abs(strtotime(date("Y-m-d")) - strtotime($ArrivalDate))/(60*60*24)));
just change your current date function format so it will give your correct answer means 26 days.
Use DateTime class :
$today = new DateTime;
$oneWeekLater = clone $today;
$oneWeekLater->modify('+1 week');
$diff = $today->diff($oneWeekLater);
echo $diff->format('Y-m-d H:i:s');
http://www.php.net/manual/en/class.datetime.php
http://www.php.net/manual/en/class.dateinterval.php
$diff = strtotime(date("d/m/Y")) - strtotime($ArrivalDate);
echo "Difference is $diff seconds\n";
$days = floor($diff/(3600*24));
echo "Difference is $days days\n";
You can also do it at the database level using the DATEDIFF() function.
http://www.w3schools.com/SQl/func_datediff_mysql.asp
$days = date("d", $timestamp1) - date("d", $timestamp2);
Try this
$ArrivalDate = '2013-05-03';
echo $daydiff=floor((abs(strtotime(date("Y-m-d")) - strtotime($ArrivalDate))/(60*60*24)));
Your date function was not in proper format as that of arrival date

how to check if a date is three days before today

Hey i would like to know if there is any script (php) that could check if a specified date three days before today.
say..
$d1 = date("Y-m-d", filemtime($testfile));
$d2 = date("Y-m-d");
now i would like to know how to compare this two dates to check if d1 is atleast 3days ago or before d2
any help would be gladly appreciated.
Why not to use DateTime object.
$d1 = new DateTime(date('Y-m-d',filemtime($testfile));
$d2 = new DateTime(date('Y-m-d'));
$interval = $d1->diff($d2);
$diff = $interval->format('%a');
if($diff>3){
}
else {
}
Assuming you wish to test whether the file was modified more than three days ago:
if (filemtime($testfile) < strtotime('-3 days')) {
// file modification time is more than three days ago
}
Just check it with timestamp:
if (time() - filemtime($testfile) >= 3 * 86400) {
// ...
}
use date("Y-m-d", strtotime("-3 day")); for specific date
you can also use
strtotime(date("Y-m-d", strtotime("-3 day")));
to convert it to integer before comparing a date string
well, stunned to see no one is using mktime() function,
it makes the job simple
for example your input date is :10/10/2012
mktime convert it to unix time stamp
$check_date=mktime(0,0,0,10,**10+3**,2012);
we can perform any operations weather +,-,*,/
use timestamp instead of date,
$d1 = filemtime($testfile);
$now = time();
if ($now - $d1 > 3600*24*3) {
..
}

how to find number of days by subtracting previous date from current date

Is it possible to find the no of days between two date fields.
i want to remove the user if user does not login within 30 days.
on every login login_date field will update.
i want to subtract two fields login_date and current_date
and if answer is 30 or greater than 30 it will delete that user.
i am new in php and need help..
i am working on localhost.
I suggest to use DateTime and DateInterval objects.
$date1 = new DateTime("2007-03-24");
$date2 = new DateTime("2009-06-26");
$interval = $date1->diff($date2);
echo "days difference ".$interval->d." days ";
read more php DateTime::diff manual
If you use timestamp format - you can use condition:
$month = 30*86400;
if ($current_date - $login_date > $month){
delete_user();
}
If you use datetime format - you can transform this format to timestamp with function strtotime
Hi try this function will get number of days between two dates.
function dateDiff($start, $end) {
$start_ts = strtotime($start);
$end_ts = strtotime($end);
$difference = $end_ts - $start_ts;
return round($difference / 86400);
}
thanks
Following will return exact days between two dates.
$last_login_date = "2012-04-01";
$current_date = "2012-04-30";
echo "Days: ".round(abs(strtotime($current_date)-strtotime($last_login_date))/86400);
Hope this helps.

How to calculate the number of years married?

I have a line of text as follows...
"Now married for XXX years, my wife and I are excited for the future."
Our wedding date is: June 7th, 2008
So, currently it reads:
"Now married for two years, my wife and I are excited for the future."
What php code can I put in the XXX space to automatically insert the number of years we have been married?
<?php
$married = new DateTime('2009-10-11');
$currentdate = new DateTime();
$interval = $married->diff($currentdate);
echo $interval->format('%y years');
?>
Something along those lines should do the trick. I haven't run this code, so you may need to tweak it a bit but it should get you started.
What you can do is subtract the current date and the anniversary date. use a function like one that is displayed here:
http://www.ozzu.com/programming-forum/subtracting-date-from-another-t29111.html
<?
$anniv = new DateTime('June 7th, 2008');
$now = new DateTime();
$interval = $now->diff($anniv, true);
echo 'Now married '.$interval->y.' years';
?>
The DateTime objects that people have used so far only work if you have a newer version of PHP. Here's a solution without them. Finding just the number of years is pretty easy.
<?php
$date1 = strtotime("June 7th, 2008"); //Get general timestamp for day
$today = time(); //Today's date
$secs = $today - $date1; //Get number of seconds passed since $date1 til $today
$years = floor($secs / (60*60*24*365)) //Derive years from seconds using number of seconds in a year
echo $years;
?>
or, in a single line of code:
<?php
$years = floor((time() - strtotime("June 7th, 2008")) / (60 * 60 * 24 * 365));
?>

Get absolute days away

I want to get the absolute days away a datetime is from today. For example, i would like to know if a date is 2 days away, or 78 days away, or even 5,239 days away (not likely, but you get the idea). I am using an MS SQL database which is returning datetimes where the time components are all 00:00:00.
date_diff returns relative values that you then have to do some crazy math with to get absolute dates do to calculating months, years, etc.
Also, i am having issues getting the date component only of today's date in php.
Edit:
Thanks to mr. w. This is what i ended up with:
$date = $row['AirdateDateTime'];
$today = date_create(date("Y-m-d"));
$away = date_diff($today, $date);
$d = $away->format("%R%a");
The date_create() part was the part i was originally missing to convert to an actual datetime. Also, the format needs to be %R%a. Using %R%d only works for dates in this month.
The date_diff() function (really, the DateTime::diff() method) is what you want, and it's actually not hard. In fact, I think the example in the docs is exactly what you're after:
<?php
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%d days');
?>
or
<?php
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%d days');
?>
What's returned is a DateInterval object, which you can format any way you want with its format() method. Above, it's being formatted to days, but you have a ton of options; see http://us.php.net/manual/en/dateinterval.format.php.
You shouldn't need to do any math yourself.
[EDIT - forgot this part]
As for getting the date component of today's date, you can do something like this:
<?php
echo date('Y-m-d');
?>
See http://us.php.net/manual/en/function.date.php.
Try this
$date1 = new DateTime('2012-10-28 00:00:00',new DateTimeZone('Europe/London'));
$date2 = new DateTime('2012-10-28 03:00:00',new DateTimeZone('Europe/London'));
$interval = date_diff($date1, $date2);
$format = '%y years, %m months, %d days, %h hours, %i minutes, %s seconds, %a total days %R';
echo $interval->format($format);
if want to change the format try this
http://www.w3schools.com/php/func_date_date.asp
It's probably easiest to convert to unix timestamps (seconds since 1970) and then get the difference.
strtotime() and time() are your friends.
An alternative to what has already been suggested is the DateTime library:
$today = date("Y-m-d");
$today = new DateTime($today);
$future = new DateTime('2010-10-25');
$interval = $today->diff($future);
echo $interval->format('%d days away'); //outputs 17 days away
It sounds like what you want is
<?php
$yourDate = '2010-10-05';
echo ciel((strtotime($yourDate) - time()) / 60 / 60 / 24);

Categories