Find difference between two dates in PHP or MySQL - php

This query does not return the records for january, but it returns records for february.
SELECT EventAsstCharged,CustomerName,EventID ,EventName,EventExpectedCharges,EventActuallyCharged,EventUserCharged,date_format(EventDate,'%d-%m-%Y') as EventDate ,EventTime FROM tblevent WHERE Status=1 AND date_format(EventDate,'%d-%m-%Y') between '01-01-2011' AND '20-02-2011' AND EntryUser=2 AND Status=1 ORDER BY EventID DESC
How to find the age between two dates using PHP or MySQL?
2009-09-24 21:09:36 2010-03-04 13:24:58

<?php
$diff = strtotime('2010-03-04 13:24:58') - strtotime('2009-09-24 21:09:36');
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

You can use this excellent function by Added Bytes to find it, I think.
echo datediff('yyyy', '2009-09-24 21:09:36', '2010-03-04 13:24:58);
Check out the function parameters for more information.

I found that the easiest way to find the difference between two dates is this one:
<?php
// Get current time, or input time like in $date2
$date1 = time();
// Get the timestamp of 2011 July 28
$date2 = mktime(0,0,0,7,28,2011);
?>
<?php
$dateDiff = $date2 - $date1;
$fullDays = floor($dateDiff/(60*60*24));
echo "$fullDays";
?>
Source: http://www.phpf1.com/tutorial/php-date-difference.html

function dateDiff($endDate, $beginDate)
{
$date_part1=explode(" ", $beginDate);
$date_part2=explode(" ", $endDate);
$date_parts1=explode("-", $date_part1[0]);
$date_parts2=explode("-", $date_part2[0]);
$start_date=gregoriantojd($date_parts1[0], $date_parts1[1], $date_parts1[2]);
$end_date=gregoriantojd($date_parts2[0], $date_parts2[1], $date_parts2[2]);
return $end_date - $start_date;
}

I fixed my ticket age using the following MySQL query.
DATEDIFF(CURDATE(),SUBSTR(ticket.created,1,10)) AS ticket_age

Related

How to retrieve the number of days from a PHP date interval?

I am trying to retrieve the number of days for a PHP interval. When I run the following piece of code on http://sandbox.onlinephpfunctions.com/:
$duration = new \DateInterval('P1Y');
echo $duration->format('%a');
echo "Done";
I get:
(unknown)Done
What am I doing wrong?
The '%a' will return the number of days only when you take a time difference otherwise it will return unknown.
You can use '%d' to get the days but it will also return 0 in the case of new \DateInterval('P1Y') as it does not convert years to days.
One easy way to get the number of days is to create a DateTime at zero time, add the interval to it, and then get the resulting timestamp:
<?php
$duration = new \DateInterval('P1Y');
$intervalInSeconds = (new DateTime())->setTimeStamp(0)->add($duration)->getTimeStamp();
$intervalInDays = $intervalInSeconds/86400;
echo $intervalInDays;
echo " Done";
The problem is here:
$duration->format('%a');
As the manual says, "Total number of days as a result of a DateTime::diff() or (unknown) otherwise".
You need a valid dateInterval object returned by DateTime's diff() method to make the "a" parameter work with DateInterval::format() function:
$now = new DateTime(date('Y-m-d H:i:s'));
$duration = (new DateTime("+1 year"))->diff($now);
echo $duration->format('%a');
Looks like if the DateInterval object is not created by DateTime::diff(), it won't work.
Hope it helps.
You have to create the interval with real dates:
<?php
$interval = date_diff(new DateTime, new DateTime('+1 year'));
echo $interval->format('%a'), PHP_EOL; // 365
if you want something aware of the year or month context, use this, february will return 28 days, leap years will have their additional day
function interval2days($day, $interval) {
$date = clone $day;
$start = $date->getTimeStamp();
$end = $date->add($interval)->getTimeStamp();
return ($end-$start)/86400;
}

How to get difference between two day in php

I have on function which passing some parameter the like
everyWeekOn("Mon",11,19,00)
I want to compute the difference between the current day (e.g. 'Fri')
and passed parameter day i.e. Mon.
The output should be:
The difference between Mon and Fri is 3
I tried it like this
$_dt = new DateTime();
error_log('$_dt date'. $_dt->format('d'));
error_log('$_dt year'. $_dt->format('Y'));
error_log('$_dt month'. $_dt->format('m'));
But know I don't know what to do next to get the difference between the two days.
Note that this question is different from How to calculate the difference between two dates using PHP? because I only have a day and not a complete date.
Just implement DateTime class in conjunction with ->diff method:
function everyWeekOn($day) {
$today = new DateTime;
$next = DateTime::createFromFormat('D', $day);
$diff = $next->diff($today);
return "The difference between {$next->format('l')} and {$today->format('l')} is {$diff->days}";
}
echo everyWeekOn('Mon');
$date = new DateTime('2015-01-01 12:00:00');
$difference = $date->diff(new DateTime());
echo $difference->days.' days <br>';
You can find no. of days in two days by using this code
<?php
$today = time();
$chkdate = strtotime("16-04-2015");
$date = $today - $chkdate;
echo floor($date/(60*60*24));
?>
Please use this may this help you

Add 1 year to a date

I have a date 01/31/2014, and I need to add a year to it and make it 01/31/2015. I am using
$xdate1 = 01/31/2014;
$xpire = strtotime(date("m/d/Y", strtotime($xdate1)) . " +1 year");
But it is returning 31474800.
Waaaay too complicated. You're doing multiple date<->string conversions, when
php > $x = strtotime('01/31/2014 +1 year');
php > echo date('m/d/Y', $x);
01/31/2015
would do the trick.
Another way is below:
<?php
$date = new DateTime('2014-01-31');
$date->add(new DateInterval('P01Y'));
echo $date->getTimestamp();
?>
There are 2 mistakes here.
You are missing the quote sign " when assigning to $xdate1. It should be
$xdate1 = "01/31/2014";
And the second, to get "01/31/2015", use the date function. strtotime returns a timestamp, not a date format. Therefore, use
$xpire = date("m/d/Y", strtotime(date("m/d/Y", strtotime($xdate1)) . " +1 year"));
May I introduce a simple API extension for DateTime with PHP 5.3+:
$xdate1 = Carbon::createFromFormat('m/d/Y', '01/31/2014');
$xpire = $xdate1->addYear(1);
First make $xdate1 as string value like
$xdate1 = '01/31/2014';
then apply date function at it like bellow
$xpire = date('m/d/Y', strtotime($xdate1.' +1 year')); // 01/31/2015

Splitting Datetime into a date and a time value

Can someone give me a quick and dirty way to split a datetime (28-1-2011 14:32:55) into just the date (28-1-2011) and the time ( 14:32 ) or even better (2:32 PM) using PHP. Using a mySQL database as well.
Cheers
If you're using PHP > 5.2:
$myvalue = '28-1-2011 14:32:55';
$datetime = new DateTime($myvalue);
$date = $datetime->format('Y-m-d');
$time = $datetime->format('H:i:s');
Prior to PHP 5.2 mhitza gave a good answer.
In php you can use the date and strtotime functions for easy extraction.
$datetime = "28-1-2011 14:32:55";
$date = date('Y-m-d', strtotime($datetime));
$time = date('H:i:s', strtotime($datetime));
if your source of data is MySQL:
SELECT DATE( date_field ) AS date_part, TIME( date_field ) AS time_part ....
http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_time
http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_date
Edit :
to answer the question from comments (example):
WHERE DATE( date_field ) > '2017-01-01'
One simple instruction will do the trick
explode will transform datetime to an array
and list will sort the datetime array into its needed values
$datetime = "28-1-2011 14:32:55";
list($date, $time)=explode(' ', $datetime);
// check the result
echo "date:". $date;
echo "<br>time:". $time;
// further more you can easily split the date into
// year month and day
list($year, $month, $day)=explode('-', $date);
If you looking for a really quick and dirty solution.
$datetime = "28-1-2011 14:32:55";
$date_arr= explode(" ", $datetime);
$date= $date_arr[0];
$time= $date_arr[1];
if you want to parse in the date from your Mysql and you want to remove time
then you can use this function
$date1=date("Y-m-d",strtotime('$your database field'))
We can easily split DateTime(28-1-2011 14:32:55) into date and time in MySQL.
select SUBSTRING_INDEX("28-1-2011 14:32:55", " ",1) into #dateOnly;
select #dateOnly;
The output will be- 28-1-2011(Here we split the date from the DateTime)
select SUBSTRING_INDEX("28-1-2011 14:32:55", " ",-1) into #timeOnly;
select #timeOnly;
The output will be- 14:32:55(Here we split the time from the DateTime)
We can covert the time to am and pm format also
select SUBSTRING_INDEX("28-1-2011 14:32:55", " ",-1) into #timeOnly;
SELECT TIME_FORMAT(#timeOnly, "%h %i %s %p")into #time;
select #time;
The time format will become 02 32 55 PM

Behavior of <?php echo date("H:i:s", 0);?>

I used :
<?php
echo date("H:i:s", $var_time_diff);
?>
to construct a time between two dates.. and in my head it was
$var_time_diff = 36000 = display 10:00:00 for 10 hours.
But in fact
<?php echo date("H:i:s", 0);?>
display 01:00:00 and not 00:00:00.
So we have
$date_a = "18:15:04";
$date_b = "23:15:04";
$diff = strtotime($date_b) - strtotime($date_a);
All is ok for the moment $diff is 5 hours but if we display date like this:
echo date("H:i:s", $diff);
it will be "06:00:00".
So something wrong with my php config or it's a normal behavior for php function date?
The date() function uses your current time zone. If you want to ignore your configured time zone, use date_default_timezone_set() or use gmdate().
You're in some timezone other than UTC. Try:
<?php
date_default_timezone_set('UTC');
echo date("H:i:s",0) . "\n";
I'm not sure why, but date outputs the current hour in your example, make a timestamp from your seconds first and it works. I'll be following this question for a deeper explanation though.
$date_a = "18:15:04";
$date_b = "23:15:04";
$diff = strtotime($date_b) - strtotime($date_a);
echo date("H:i:s", mktime(0,0,$diff));
edit: ah, so it adjusts to your current timezone, so does mktime, so the effect is negated.
use mktime, and min 1 for hour # $diff

Categories