Calculating MySQL and PHP date difference in days - php

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

Related

PHP Date - Time difference formatting

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

php add x weeks to a date and then find the next given day

I can add x week to my date
//$ultima_azione <--- 2015/07/15
//$data['intervallo'] <---- 5
$mydate = date("Y-m-d",strtotime($ultima_azione." +".$data['intervallo']." weeks"));
now how can i give a day starting from that week
example:
//$mydate + "next Monday" -----> final date
and this ve to work like, if today is Monday and i add weeks to jump to an other Monday and then i select the next Monday the week don't ve to change
The simplest way would be to use strtotime. It can do date calculations based on a textual representation of the delta:
$mydate = strtotime('+3 weeks');
It also accepts a second parameter, which is a timestamp to start from when doing the calculation, so after you get the offset in weeks, you can pass the new date to a second calculation:
// Get three weeks from 'now' (no explicit time given)
$mydate = strtotime('+3 weeks');
// Get the Monday after that.
$mydate = strtotime('next Monday', $mydate);
See strtotime documentation for more examples of notations that you can use.
I would highly recommend using PHP's built-in DateTime class for any date and time logic. It's a much better API than the older date and time functions and creates much cleaner and easier to read code.
For example:
// Current date and number of weeks to add
$date = '2015/07/15';
$weeks = 3;
// Create and modify the date.
$dateTime = DateTime::createFromFormat('Y/m/d', $date);
$dateTime->add(DateInterval::createFromDateString($weeks . ' weeks'));
$dateTime->modify('next monday');
// Output the new date.
echo $dateTime->format('Y-m-d');
References:
DateTime.
DateTime::createFromFormat
DateTime::add
DateTime::modify
DateInterval::createFromDateString
DateTime::format
Are you looking for something like this?
$today = time();
$weeks = 2;
// timestamp 2 weeks from now
$futureWeeks = strtotime("+ ".$weeks." weeks");
// the next monday after the timestamp date
$futureMonday = strtotime("next monday",$futureWeeks);
echo date("Y-m-d", $futureMonday);
// or in one line
echo date("Y-m-d", strtotime("next monday", strtotime("+ ".$weeks." weeks")));
PHP is using an unix timestamp for date calculations. Functions as date() and strtotime() using a timestamp as an optional second parameter. This is used a reference for formatting and calculations. If no timestamp is passed to the function the current timestamp is used (time()).
I have the answer here. This will show the next wednesday every 2 weeks and the first date to start from would be the 10th.
I have also added in an estimated delivery which would be 6 weeks after that date.
We will be placing our next order for this on:
<?php
$date = '2020/05/26';
$weeks = 2;
$dateTime = DateTime::createFromFormat('Y/m/d', $date);
$dateTime->add(DateInterval::createFromDateString($weeks . ' weeks'));
$dateTime->modify('wednesday');
echo $dateTime->format('d/m/Y');
?>
Expected delivery for the next order will be:
<?php
$date = '2020/05/26';
$weeks = 2;
$dateTime = DateTime::createFromFormat('Y/m/d', $date);
$dateTime->add(DateInterval::createFromDateString($weeks . ' weeks'));
$dateTime->modify('+42 days next wednesday');
echo $dateTime->format('d/m/Y');
?>
If anyone can confirm this is correct that would be great.

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 convert unixtimestamp to mysql date format

I'm writing code to subtract two dates. It is for a contract type thingy, where user gets to see the number of days left for his contract to complete. Something like start_date_time="today" and end_date_time=y where the value of y is retrieved from the database (DATETIME type). It is in the mysql datetime format (yyyy-mm-dd HH:mm:ss).
<?php
include_once '../include/connections.php';
$id =$_REQUEST['uid'];
$result= mysql_query("SELECT * FROM data WHERE uid = '$id'");
$test = mysql_fetch_array($result);
echo $test[14];
echo "<br /><br />";
$today=time();
$enddate=strtotime('$test[14]');
$timediff = $enddate - $today;
$days=intval($timediff/86400);
$remaining=$timediff%86400;
$hours=intval($remaining/3600);
$remaining=$remaining%3600;
$mins=intval($remaining/60);
$secs=$remaining%60;
echo "<br>".$days.' days '.$hours.' hours '.$mins.' minutes and '.$secs.' seconds.';
?>
When I echo $test[14];, I get the date and time as stored in the database which is
(2012-09-26 00:00:00)
When i echo $today; then i get it in this format 1348381896. Now, how do i convert this format to the one retrieved from the db so that i can subtract the 2 dates and get the number of days and time left?
You can use these 2 functions to convert dates to each other,
Use this for timestamp to MySQL datetime:
$timestamp = '1348381896';
$date = date('Y-m-d H:i:s', $timestamp);
echo $date;
Use this one for MySQL datetime to timestamp:
$date = '2012-09-26 00:00:00';
$timestamp = strtotime($date);
echo $timestamp;
Also if you are willing to Subtract your dates in MySQL side, you can use the DATEDIFF and or TIMEDIFF functions:
Also you can work with timestamps in MySQL too, using TIMESTAMPDIFF and UNIX_TIMESTAMP functions ...
You could use PHP's DateTime classes for this:-
$today = new DateTime();
$mysqlDate = "2012-12-15 13:40:20"; //for example
// To match your code this would be $mysqlDate = $test[14];
$mysqlFormat = 'Y-m-d H:i:s';
$endDate = DateTime::createFromFormat($mysqlFormat, $mysqlDate);
$diff = $today->diff($endDate);
echo "You have {$diff->d} days, {$diff->h} hours and {$diff->m} minutes left";
This will give the following output:-
You have 22 days, 6 hours and 5 minutes left
(This will change depending on when you run the code).
$diff is an instance of DateInterval.
date formats acceptable to DateTime::createFromFormat() can be found here http://www.php.net/manual/en/function.date.php

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.

Categories