I am creating PHP function that will return difference between two dates in a format: 2 Months, 3 Weeks, 6 Days, 3 Hours. I have tried to use PHP DateTime class, but it returns only Months, Days and Hours and I can not find a way to calculate Weeks.
This is my function:
public function DateTimeDifference($FromDate, $ToDate) {
$FromDate = new DateTime($FromDate);
$ToDate = new DateTime($ToDate);
$Interval = $FromDate->diff($ToDate);
$Difference["Hours"] = $Interval->h;
$Difference["Days"] = $Interval->d;
$Difference["Months"] = $Interval->m;
return $Difference;
}
Now, I need $Difference["Weeks"] also included in return data.
EDIT: I know I can divide Days with 7 and get weeks, but this does not result right. For example: 2 Months, 14 Days, 3 Hours - When I divide 14 days with 7 I will get this: 2 Months, 2 Weeks, 14 Days, 3 Hours and now this is not same period.
public function DateTimeDifference($FromDate, $ToDate) {
$FromDate = new DateTime($FromDate);
$ToDate = new DateTime($ToDate);
$Interval = $FromDate->diff($ToDate);
$Difference["Hours"] = $Interval->h;
$Difference["Weeks"] = floor($Interval->d/7);
$Difference["Days"] = $Interval->d % 7;
$Difference["Months"] = $Interval->m;
return $Difference;
}
// this will only work from previous dates
// difference between utc date time and custom date time
function FromUtcToCustomDateTimeDifference($ToDate)
{
// Takes Two date time
$UTC_DATE = new DateTime('now', new DateTimeZone('UTC'));
$UTC_DATETIME = $UTC_DATE->format('Y-m-d H:i:s');
// add your own date time 1
$datetime1 = date_create(UTC_DATETIME);
$datetime2 = date_create($ToDate);
$Interval = date_diff($datetime1, $datetime2);
// Count Number Of Days Difference
$Day = $Interval->format('%a');
if($Day > 1)
{
$Month = $Interval->format('%m');
$Year = $Interval->format('%y');
$Week = (int)($Interval->format('%a')/7);
if($Year<1)
{
if($Day <= 7)
{
return $Day > 1 ? $Day.= " days ago" : $Day .= " day ago";
}
else if($Month<1)
{
return $Week > 1 ? $Week.= " weeks ago" : $Week .= " week ago";
}
return $Month > 1 ? $Month.= " months ago" : $Month .= " month ago";
}
else
{
return $Year > 1 ? $Year.= " years ago" : $Year .= " year ago";
}
}
else
{
return "today";
}
}
Related
Here i am doing remaining count town time, Like suppose event going to start 2018-04-18 04:30 PM,Suppose current time is 2018-04-18 04:10 PM means i want to display like 20 Minutes left,I witten the code but it is showing wrong result
My PHP code:
<?php
date_default_timezone_set('UTC');
date_default_timezone_set('Asia/Kolkata');
function timeAgo($logintime)
{
$start_date = new DateTime($logintime);
$since_start = $start_date->diff(new DateTime(date("Y-m-d h:i:s")));//2018-04-18 04:10 PM
if( intval($since_start->format('%Y') ) >= 1){
$timeago = $since_start->format('%Y years');
}
else if(intval($since_start->format('%m')) >= 1){
$timeago = $since_start->format('%m months ');
}
else if(intval($since_start->format('%a')) >= 1){
$timeago = $since_start->format('%a days ');
}
else if(intval($since_start->format('%h')) >= 1){
$timeago = $since_start->format('%h hours ');
}
else if(intval($since_start->format('%i')) >= 1){
$timeago = $since_start->format('%i minutes ');
}
else if(intval($since_start->format('%s')) >= 1){
$timeago = $since_start->format('%s seconds ');
}
return $timeago;
}
echo timeAgo('2018-04-18 04:30 PM');
?>
I am getting result like this
12 hours
My Expected output is
20 Minutes left
Your just give the now DateTime only. You don't want to declare the time format. And you just use this time zone only date_default_timezone_set('Asia/Kolkata');. Here is code:
date_default_timezone_set('Asia/Kolkata');
function timeAgo($logintime)
{
$start_date = new DateTime($logintime);
$since_start = new DateTime();
$interval = $since_start->diff($start_date);
$timeago = $interval->format("%a days, %h hours, %i minutes, %s seconds");
if($since_start < $start_date){
return $timeago. ' ago';
}else{
return 'This Event Passed';
}
}
echo timeAgo('2018-04-19 05:50 PM');
Out put:
1 days, 0 hours, 56 minutes, 28 seconds ago
This question already has answers here:
Finding the number of days between two dates
(34 answers)
Closed 3 months ago.
I want to do is to count the days between two dates excluding the weekends and i;m done doing that using the function below. But whenever the $startDate is greater than the $endDate i can't get the proper result. I try to use if ($startDate>$endDate) and i'm stock with that condition and honestly don't know what is the next step.
function getWorkingDays($startDate,$endDate){
// do strtotime calculations just once
$startDate = strtotime($startDate);
$endDate = strtotime($endDate);
//The total number of days between the two dates. We compute the no. of seconds and divide it to 60*60*24
//We add one to inlude both dates in the interval.
$days = ($endDate - $startDate) / 86400 + 0;
$no_full_weeks = floor($days / 7);
$no_remaining_days = fmod($days, 7);
//It will return 1 if it's Monday,.. ,7 for Sunday
$the_first_day_of_week = date("N", $startDate);
$the_last_day_of_week = date("N", $endDate);
// If one of the value is empty it will return "0"
if ($startDate == '' || $endDate == '')
return "0"; // Default value
//---->The two can be equal in leap years when february has 29 days, the equal sign is added here
//In the first case the whole interval is within a week, in the second case the interval falls in two weeks.
if ($the_first_day_of_week <= $the_last_day_of_week) {
if ($the_first_day_of_week <= 6 && 6 <= $the_last_day_of_week) $no_remaining_days--;
if ($the_first_day_of_week <= 7 && 7 <= $the_last_day_of_week) $no_remaining_days--;
}
else {
// (edit by Tokes to fix an edge case where the start day was a Sunday
// and the end day was NOT a Saturday)
// the day of the week for start is later than the day of the week for end
if ($the_first_day_of_week == 7) {
// if the start date is a Sunday, then we definitely subtract 1 day
$no_remaining_days--;
if ($the_last_day_of_week == 6) {
// if the end date is a Saturday, then we subtract another day
$no_remaining_days--;
}
}
else {
// the start date was a Saturday (or earlier), and the end date was (Mon..Fri)
// so we skip an entire weekend and subtract 2 days
$no_remaining_days -= 2;
}
}
//The no. of business days is: (number of weeks between the two dates) * (5 working days) + the remainder
//---->february in none leap years gave a remainder of 0 but still calculated weekends between first and last day, this is one way to fix it
$workingDays = $no_full_weeks * 5;
if ($no_remaining_days > 0 )
{
$workingDays += $no_remaining_days;
}
return $workingDays;
}
$startTimeStamp = strtotime("2011/07/01");
$endTimeStamp = strtotime("2011/07/17");
$timeDiff = abs($endTimeStamp - $startTimeStamp);
$numberDays = $timeDiff/86400; // 86400 seconds in one day
// and you might want to convert to integer
$numberDays = intval($numberDays);
OR
function dateDiff($start, $end) {
$start_ts = strtotime($start);
$end_ts = strtotime($end);
$diff = $end_ts - $start_ts;
return round($diff / 86400);
}
echo dateDiff("2011-02-15", "2012-01-16").'days';
//Get number of days deference between current date and given date.
echo dateDiff("2011-02-15", date('Y-m-d')).'days';
For Count days excluding use below code
$start = new DateTime('7/17/2017');
$end = new DateTime('7/24/2017');
$oneday = new DateInterval("P1D");
$daysName = array('Mon', 'Tue', 'Wed', 'Thu', 'Fri');
$days = array();
foreach(new DatePeriod($start, $oneday, $end->add($oneday)) as $day) {
$day_num = $day->format("N"); /* 'N' number days 1 (mon) to 7 (sun) */
if($day_num < 6) { /* weekday */
$days[$day->format("Y-m-d")] = date('D', strtotime($day->format("Y-m-d")));;
}
}
echo "<pre>";
print_r($days);
echo count($days);
This will check whether start date is less than end date. If yes, then it will display the days.
<?php
if($days = getWorkingDays("2017-05-01","2018-01-01")){
echo $days;
}
function getWorkingDays($startDate,$endDate){
$startDate = strtotime($startDate);
$endDate = strtotime($endDate);
if($startDate <= $endDate){
$datediff = $endDate - $startDate;
return floor($datediff / (60 * 60 * 24));
}
return false;
}
?>
Output: 245
Functions Used:
strtotime(): The strtotime() function parses an English textual datetime into a Unix timestamp
floor(): The floor() function rounds a number DOWN to the nearest integer
Edit-1: Getting Days After Excluding Weekends (saturdays & sundays)
//getWorkingDays(start_date, end_date)
if($days = getWorkingDays("2017-05-01","2018-01-01")){
echo $days;
}
function getWorkingDays($startDate,$endDate){
$days = false;
$startDate = strtotime($startDate);
$endDate = strtotime($endDate);
if($startDate <= $endDate){
$datediff = $endDate - $startDate;
$days = floor($datediff / (60 * 60 * 24)); // Total Nos Of Days
$sundays = intval($days / 7) + (date('N', $startDate) + $days % 7 >= 7); // Total Nos Of Sundays Between Start Date & End Date
$saturdays = intval($days / 7) + (date('N', $startDate) + $days % 6 >= 6); // Total Nos Of Saturdays Between Start Date & End Date
$days = $days - ($sundays + $saturdays); // Total Nos Of Days Excluding Weekends
}
return $days;
}
?>
Sources:
calculate sundays between two dates
The intval() function is used to get the integer value of a variable.
See Description date('N', $date) : N - The ISO-8601 numeric representation of a day (1 for Monday, 7 for Sunday)
There is the script of code for do this.
<?php
$now = time(); // or your date as well
$your_date = strtotime("2010-01-01");
$datediff = $now - $your_date;
echo floor($datediff / (60 * 60 * 24));
?>
or
$datetime1 = new DateTime("2010-06-20");
$datetime2 = new DateTime("2011-06-22");
$difference = $datetime1->diff($datetime2);
echo 'Difference: '.$difference->y.' years, '
.$difference->m.' months, '
.$difference->d.' days';
print_r($difference);
try this
public function datediff($sdate,$edate){
$diffformat='%a';
$date1 = date_create($sdate);
$date2 = date_create($edate);
$diff12 = date_diff($date2, $date1);
$days = $diff12->format($diffformat) + 1;}
EDIT: I noticed in the comment you want to exclude the weekend day/days (however you didn't mention that in your post !)
you can add the number of days you want to exclude from the week
you can use DateTime::diff and use the option for absolute result (positive difference always)
<?php
function daysBetween2Dates($date1, $date2, $execludedDaysFromWeek = 0)
{
try{
$datetime1 = new \DateTime($date1);
$datetime2 = new \DateTime($date2);
}catch (\Exception $e){
return false;
}
$interval = $datetime1->diff($datetime2,true);
$days = $interval->format('%a');
if($execludedDaysFromWeek < 0 || $execludedDaysFromWeek > 7){
$execludedDaysFromWeek = 0 ;
}
return ceil($days * (7-$execludedDaysFromWeek) / 7);
}
Usage Example
// example 1 : without weekend days, start date is the first one
$days = daysBetween2Dates('2016-12-31','2017-12-31');
echo $days;
// example 2 : without weekend days, start date is the second one
$days = daysBetween2Dates('2017-12-31', '2016-12-31');
echo "<br>\n" .$days;
// example 3 : with weekend days, it returns 6 days for the week
$days = daysBetween2Dates('2017-12-31', '2017-12-24',-1);
echo "<br>\n" .$days;
exit;
this outputs
365
365
6
live demo (https://eval.in/835862)
use date_diff() which returns the difference between two DateTime objects.
$diff=date_diff($startDate,$endDate);
I'm having trouble getting "weeks" in DateTime::diff function
Here's my code:
$date1 = new DateTime("2017-05-14");
$date2 = new DateTime("2017-06-14");
$interval = $date1->diff($date2);
echo $interval->m.' '.($interval->m > 1 ? 'months' : 'month');
It worked if I'm going to get the "month" count, but I want to get the weeks before turning it into a month:
We have 4 weeks in a month (4.34524 to be exact from Google Unit Converter), if the difference between start date and the date today exceeds 4 weeks, it should output "1 month" and so on..
Code (Demo):
$date1 = new DateTime("2017-06-1");
$date2 = new DateTime("2017-06-15");
$interval = $date1->diff($date2);
//var_export($interval);
if($interval->m>0){ // check if >= 1 month
echo "{$interval->m} month",($interval->m>1?'s':'');
}else{
$weeks=floor($interval->days/7); // if not yet 1 month, calc weeks
echo "$weeks week",$weeks!=1?'s':'';
}
// output: 2 weeks
Calculate days and then divide by 7 for week.
Try this code :
$date1 = new DateTime("2017-05-14");
$date2 = new DateTime("2017-06-14");
$interval = $date1->diff($date2);
$week = floor($date1->diff($date2)->days/7);
echo $week;
if($week > 4)
{
echo $interval->m.' '.($interval->m > 1 ? 'months' : 'month');
}
you could do this to get weeks and then make the condition:
$daysInAweek = 7;
$weeks = ($interval->days)/$daysInAweek;
if($weeks >= 4) {
echo 'is a month';
}
because a week have 7 days.
I tried to find out difference between today date and specific day with format Ymd.
How to check whether specific day is greater than 30 days from today?
For example:
$date1 = '20160315'; // 2016-03-15
$date2 = '20160115'; // 2016-01-15
Try this
$date1=date_create('20160315');
$date2=date_create('20160115');
$diff=date_diff($date1,$date2);
$days = $diff->format("%a");
if($days > 30) do something
So simple...
$date1 = '20160315'; // 2016-03-15
$date2 = date(Ymd); // 2016-01-15
$day_difference = $date1 - $date2
if($day_difference > 30) {
echo 'specific day is greater than 30 days from today';
} else {
echo 'specific day is less than 30 days from today';
}
Try this:
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-11-13');
$interval = $datetime1->diff($datetime2);
$int = $interval->format('%R%a');
if($int > +30) {
echo "Greater than 30 days";
} else {
echo "Less than 30 days";
}
Calculate between two Dates duration in PHP
Example :
Start Date : 01-01-2016
End Date : 31-01-2016
I get Answer is 30 days but I want result is 1 month
More Examples:
01-01-2016 to 31-01-2016 = 1 month
01-02-2016 to 29-02-2016 =1 month
01-03-2016 to 31-03-2016 =1 month
show on ..
<?php
$date1 = '2000-01-20';
$date2 = '2000-02-20';
$ts1 = strtotime($date1);
$ts2 = strtotime($date2);
$year1 = date('Y', $ts1);
$year2 = date('Y', $ts2);
$month1 = date('m', $ts1);
$month2 = date('m', $ts2);
echo $diff = (($year2 - $year1) * 12) + ($month2 - $month1);
?>
I think this will help you.
Here is what I tried.
Find the first and last day of the month of first date and compare them with the given dates. If they matches it prints "1 month" else it prints the number of days like "n days".
$date1 = "2016-02-01";
$date2 = "2016-02-29";
$output = "";
if ($date1 == date("Y-m-01", strtotime($date1)) && $date2 == date("Y-m-t", strtotime($date1))) {
$output = "1 month";
} else {
$output = ((strtotime($date2) - strtotime($date1)) / 86400 + 1) . " days";
}
echo $output;
class shahjadclass {
public function getduration($postdate) {
/* $postdate is the date where the post was created */
$assigned_time = date("Y-m-d h:i:sa");
$d1 = new DateTime($assigned_time);
$d2 = new DateTime($postdate);
$interval = $d2->diff($d1);
$datestring='';
if($interval->y>0){
$datestring=$interval->format('%y Years ago') ;
}elseif ($interval->m>0) {
$datestring=$interval->format('%m Months ago') ;
}elseif ($interval->d>0) {
$datestring=$interval->format('%d Days ago') ;
}elseif ($interval->h>0) {
$datestring=$interval->format('%h Hours ago') ;
}elseif($interval->i>0){
$datestring=$interval->format('%i Min ago') ;
}else{
$datestring=$interval->format('%s Sec ago') ;
}
return $datestring;
}
}
**
Usage
require_once('shahjadclass.php');
$myfunctions = new shahjadclass();
To get Output
$datestring=$myfunctions->getduration('createdon');
**