find the total hours in PHP by using two date [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP:find day difference between two date(“YmdHis”) reture
I have two dates
$departure_Dtae=2012-07-25T07:30:00
$arrival_date =2012-07-25T10:25:00
T means Time i.e. in 2012-07-25T10:25:00 date is 2012-07-25 and the time is 10:25:00 (hr: mts: s)
I need to find out the total hrs between these two times
I.e. in this case the total hour is 2 hr and 55 minutes
But I don't know how I calculate this in PHP
Does anyone know this?

If using PHP Version 5.3+ then you can use DateTime::diff():
<?php
function getDiff($strStart, $strEnd) {
$start = DateTime::createFromFormat("Y-m-d G:i:s", $strStart);
$end = DateTime::createFromFormat("Y-m-d G:i:s", $strEnd);
return $start->diff($end)->format('%hhrs %imins and %sseconds ');
}
var_dump(getDiff('2012-07-25 07:30:00', '2012-07-25 10:25:00'));

its simple
$departure_Dtae="2012-07-25T07:30:00";
$arrival_date ="2012-07-25T10:25:00";
$departure_Dtae= str_replace("T", " ", $departure_Dtae);
$arrival_date= str_replace("T", " ", $arrival_date);
$diff= (strtotime($arrival_date)-strtotime($departure_Dtae));
echo date("h",$diff);

Try this :
$end_time = "2008-09-05 20:59:13";
$start_time = "2008-09-05 19:00:16";
$end = date("h:i:s",strtotime($end_time));
$start = date("h:i:s",strtotime($start_time));
$diff = strtotime($end) - strtotime($start);
//convert to min and sec
$convert_min = $diff/60;
$convert_sec = $diff % 60;//seconds
//convert to hours and min
$convert_hr = floor($convert_min/60);//hours
$remainder = floor($convert_min % 60);//minutes
$total_visit = $convert_hr.":".$remainder;

You can use the DateTime object in php, which has loads of methods for manipulating dates.
DateTime::createFromFormat http://www.php.net/manual/en/datetime.createfromformat.php and DateTime::diff http://www.php.net/manual/en/datetime.diff.php would be the functions you would need to perform this task.
$date1 = DateTime::createFromFormat('j-M-Y H:i', '15-Feb-2009 12:45');
$date2 = DateTime::createFromFormat('j-M-Y H:i', '15-Feb-2009 13:45');
$interval = $date1->diff($date2);
echo $interval->format('H:i');

strtotime(date($arrival_date)) - strtotime(date($departure_date));
Will give you the time diff in secounds, then you can manipulate that as you wish.

Related

Add specific hours in a specific time in php [duplicate]

This question already has answers here:
Add time in PHP
(4 answers)
Closed 5 years ago.
Following is code that helps in adding specific hours in present time
date('H:i', strtotime('+1 hours'));
How should i add hours if the time and hours are dynamic. E.g I wish to add 2 hours to time 08:00, but these both things are saved in variables
$hours = "2";
$day_time = "08:00";
I tried the following but didn't work
$new_time = date($day_time, strtotime('+$hours hours'));
can anyone please tell how it can be done
try this
echo date("H:i", strtotime("+{$hours}hour ".$day_time));
Try this
$h = 2 ;
$time="08:00";
$time = date('H:i', strtotime($time.'+'.$h.' hour'));
echo $time;
Try below code,
<?php
$hours = "2";
$day_time = "08:00";
$new_time = date('H:i',strtotime($day_time.'+ '.$hours.' hour'));
echo $new_time;
?>
Output : 10:00
Using datetime would be better to avoid
"A non well formed numeric value encountered"
$date = new DateTime($day_time);
$date->modify("+".$hours." hours");
echo $date->format("H:i");
Try like this,
$hours = 2;
$day_time = "08:00";
$new_time = date('H:i',strtotime($day_time."+$hours hours"));
That's because you are using a variable inside single quotes. There are some ways to fix this:
//awful and you should avoid it
//(hard to read, unsafe use of direct variables inside strings):
$new_time = date($day_time, strtotime("+$hours hours"));
or
//still awful and you should avoid it too:
$new_time = date($day_time, strtotime('+{$hours} hours'));
or
//a little better, but still unsafe:
$new_time = date($day_time, strtotime('+' . $hours . ' hours'));
or
//better, safe because it only adds numeric values to the hours:
$new_time = date($day_time, strtotime(sprintf('+%d hours', $hours)));
or
//the ideal solution, safer to use and more professional:
$dateObj = new DateTime();
$dateObj->modify(sprintf('+%d hours', $hours));
$new_time = $dateObj->format("H:i");
That's the beauty and the curse of PHP, you can always do things in more than one way.

Number of weeks between two flexible dates - PHP

I have been looking through all the previous questions which similar to this question unfortunately non of them work for me.
I am trying to get the number of weeks between two dates.
$result = mysqli_query($con,"SELECT * FROM `test` WHERE `DateofTest` BETWEEN '" .
$startDate . "' AND '" . $endDate . "' ") or die ("Error: ".mysqli_error($con));
$startDate = $_POST['start'];
$endDate = $POST['end'];
Suppose my start date is 01/12/2014 and end date is 31/12/2014 so 4 weeks.
Here is my code
$startDate ="2014-12-01";
$endDate ="2014-12-31";
$days=($startDate - $endDate);
echo $days;
$weeks=($days / 7);
echo $weeks;
I am getting 0 result for each days and weeks.
Any ideas please.
Thanks
Something like this using the date time object will work
$d1 = new DateTime("2014-12-01");
$d2 = new DateTime("2014-12-31");
$difference_in_days = $d1->diff($d2)->days;
echo "Diff in Weeks = ".$difference_in_days/7;
You can't calculate strings. You need to convert them to dates.
You can do something like:
function get_number_of_weeks($startDate, $endDate) {
// use strtotime and substract the end date from the start date, not the otherway around
$days = strtotime($endDate) - strtotime($startDate);
// devide by seconds / hours and weeks
$weeks = $days / 3600 / 24 / 7;
// floor the amount of weeks.
return floor($weeks);
}
echo get_number_of_weeks("2014-12-01", "2014-12-31");
You cannot compare date strings and expect to get the difference.
You should use the DateTime class to compare two datetime values:
$startDate = new DateTime("2014-12-01");
$endDate = new DateTime("2014-12-31");
$diff = $startDate->diff( $endDate )->format('%d');
$weeks = floor($diff/7);
format method can return a difference in a number of ways like years/months/days/hours/minutes/seconds. More here
Try this..
<?php
$d1 ="2014-12-01";
$d2 ="2014-12-31";
$diffweek = abs(strtotime($d1) - strtotime($d2)) / 604800;
echo round($diffweek); or echo intval($diffweek);
?>

Date is not formatting time correctly PHP

Hello I try to take the difference between two dates and display it.
My problem is that the time difference I get is not the correct one.
This is my code:
$time1 = strtotime('2014-03-28 15:20:00');
$time2 = strtotime('2014-03-28 15:15:00');
$diffTime = $time1 - $time2;
echo date('H:i', $diffTime);
The result I get is:
02:05
The currect time should be this:
00:05
My guess that the date somehow takes timezone or something like this but Im not sure.
Thanks.
/****************************************
$start_date = new DateTime('23:58:40'); *These two still give
$end_date = new DateTime('00:00:00'); *a wrong answer
*****************************************/
$start_date = new DateTime('23:58:40');
$end_date = new DateTime('00:11:36');
$dd = date_diff($end_date, $start_date);
//Giving a wrong answer: Hours = 23, Minutes = 47, Seconds = 4
echo "Hours = $dd->h, Minutes = $dd->i, Seconds = $dd->s";
So what you're actually doing here is generating two UNIX timestamps (numbers) and then subtracting them. then you're passing the resulting number as if it were still a timestamp to date().
essentially $diffTime is the number of seconds between your two times. you could divide by 60 to get minutes, and so on and so forth, but PHPs DateTime objects are much better.
From the PHP docs:
http://pl1.php.net/strtotime
Note:
Using this function for mathematical operations is not advisable. It is better to use DateTime::add() and DateTime::sub() in PHP 5.3 and later, or DateTime::modify() in PHP 5.2.
try this
<?php
$time1 = strtotime('2014-03-28 15:20:00');
$time2 = strtotime('2014-03-28 15:15:00');
echo round(abs($time1 - $time2) / 60,2). " minute"
?>
Below is the solution of date time in years,days.hours,minutes and seconds.
$time1 = strtotime('2014-03-28 15:20:00');
$time2 = strtotime('2014-03-28 15:15:00');
$diffTime = $time1 - $time2;
$y = ($diffTime/(60*60*24*365));
$d = ($diffTime/(60*60*24))%365;
$h = ($diffTime/(60*60))%24;
$m = ($diffTime/60)%60;
$s = ($diffTime)%60;
echo "Minutes - " .$m;
echo "<br/>";

Difference of hours between two dates (integer) [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Calculate number of hours between 2 dates in PHP
How can I get the number of hours of difference between two dates in PHP? I need to get an integer since I want to know if is bigger or smaller than a particular value.
Try:
$date1 = "2012-11-05 12:35:00";
$date2 = "2012-11-07 14:35:00";
$diff = strtotime($date2) - strtotime($date1);
$diff_in_hrs = $diff/3600;
print_r($diff_in_hrs);
Manual
Demo
If you have an up-to-date PHP
$dateOne = new DateTime('2012-01-20 00:00:00');
$dateTwo = new DateTime('2012-01-21 02:00:00');
// Procedurally
$interval = date_diff($dateOne, $dateTwo);
// Alternatively OOP style if supported
$interval = $dateOne->diff($dateTwo);
See: http://www.php.net/manual/en/class.dateinterval.php
<?php
$time1 = time();
$time2 = mktime(0,0,0,11,13,2012); // earlier today
echo ($time1 - $time2) / 3600; // 3600 seconds in hour
?>

Calculates difference between two dates in PHP [duplicate]

This question already has answers here:
Get interval seconds between two datetime in PHP?
(8 answers)
Closed last year.
HI, i have a couple of posts in my MySql database server, one of the info content in each post is the date and time in the format datetime (Ex. 2010-11-26 21:55:09) when the post was made.
So, i want to retrive the actual date and time from the SQL server with the function NOW() and calculates how many seconds or minutes or hours or days ago was post the info.
I dont know how to create this php script but i know that for sure is allready made, so thanks for any help.
you could use the date_diff() function
http://php.net/manual/en/function.date-diff.php
Something like...
<?php
$now = time();
$then = $posttime;
$diff = date_diff($now,$then);
echo $diff->format('%R%d days'); #change format for different timescales
?>
edit --
I actually solve this issue on one of my twitter apps using this function...
function time_since ( $start )
{
$end = time();
$diff = $end - $start;
$days = floor ( $diff/86400 ); //calculate the days
$diff = $diff - ($days*86400); // subtract the days
$hours = floor ( $diff/3600 ); // calculate the hours
$diff = $diff - ($hours*3600); // subtract the hours
$mins = floor ( $diff/60 ); // calculate the minutes
$diff = $diff - ($mins*60); // subtract the mins
$secs = $diff; // what's left is the seconds;
if ($secs!=0)
{
$secs .= " seconds";
if ($secs=="1 seconds") $secs = "1 second";
}
else $secs = '';
if ($mins!=0)
{
$mins .= " mins ";
if ($mins=="1 mins ") $mins = "1 min ";
$secs = '';
}
else $mins = '';
if ($hours!=0)
{
$hours .= " hours ";
if ($hours=="1 hours ") $hours = "1 hour ";
$secs = '';
}
else $hours = '';
if ($days!=0)
{
$days .= " days ";
if ($days=="1 days ") $days = "1 day ";
$mins = '';
$secs = '';
if ($days == "-1 days ") {
$days = $hours = $mins = '';
$secs = "less than 10 seconds";
}
}
else $days = '';
return "$days $hours $mins $secs ago";
}
You pass it in a unix timestamp of the time to check (the post time) and it returns the various string.
As billythekid said, you can use the date_diff() function if you are using PHP5.3+, if you are not then there are various methods. As shown by other posters. The quickest method in MySQL if you want to know the time split in to the "hours:mins:secs" hierarchy is to use the TIMEDIFF() function.
SELECT TIMEDIFF(NOW(), '2010-11-26 12:00:00');
If you want it as seconds, use the unix timestamp features in MySQL or in PHP, you can convert MySQL dates to PHP quickly using strtotime().
Usually, you do this kind of thing in a query, but MySQL isn't very good with intervals (it would be very easy with PostgreSQL). You could convert it to unix timestamp, then it would give the number of seconds between the two dates :
SELECT UNIX_TIMESTAMP() - UNIX_TIMESTAMP(your_datetime_column);
I thought about DATEDIFF, but it only returns the number of days between the two dates.
You can do it in PHP, for instance, with DateTime class :
$date1 = new DateTime();
$date2 = new Datetime('2010-11-26 12:00:00');
var_dump($date1->diff($date2));
(There's a procedural way to do this, if you're not a fan of OOP.)
This is definitely the solution I'd use if I can't do it with the RDBMS. DateTime::diff returns a DateInterval object, which contains the number of seconds, minutes, hours, days, etc. between the two dates.
You could also do it with timestamps in PHP :
$num_sec = time() - strtotime('2010-11-26 12:00:00');
Which would return the same thing as the SQL query.
An easy solution is possible from within the SQL Query:
SELECT UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(post_date) AS seconds_ago FROM posts
Documentation here: MySQL Ref
I actually needed to do this in PHP myself and while billythekid's post was in the right direction it fell short. I've minimized the code though it should be clear that the second parameter is from a database with a DATETIME column type.
<?php
$interval = date_diff(date_create(date('Y-m-d H:i:s')), date_create($row1['date']));
echo $interval->format('%R%a days');
//Database: 2019-02-22
//PHP's date: 2018-07-07
//Result: +306 days
?>
A reminder of the obvious: you can also just use substr($interval->format('%R%a days'),1) if you need just the integer.

Categories