Calculate percentage between dates in php - php

I want to calculate the percentage (from 0 to 100) of the time elapsed between two dates (start and end) according to the current date.
For example:
$start_date = "01/01/2018";
$end_date = "31/12/2018";
$today = "30/06/2018";
Expected output:
Percentage: 50
Any idea? Thanks

You could convert all dates to timestamps and do the math from there. strtotime() will convert the dates for you, but that will interpret your dates with slashes in the english format (MM/DD/YYYY) instead of (DD/MM/YYYY). If you replace the slashes with dashes, it will read it in the DD-MM-YYYY format.
$date_timestamp = strtotime(str_replace('/', '-', $date));
Then it's just a matter of:
$total = $end_date - $start_date;
$part = $todays_date - $start_date;
$percent = $part/$total * 100;

You'd need at least three variables:
$fromDate = strtotime("01/01/2018 ");
$currentDate = time();
$toDate = strtotime("01/01/2019");
//days between From and To
$datediffA = round(($toDate- $fromDate) / (60 * 60 * 24));
//days between From and Current
$datediffB = round(($currentDate- $fromDate) / (60 * 60 * 24));
echo $datediffA;
echo $datediffB;
Will output:
365
320
Now knowing these numbers you can go on and find the percentage of one to another.
$percentage = ($datediffB*100)/$datediffA;
echo $percentage;
Will output:
87.671232876712%

Date("z") gives you the day of the year.
Your "today" returns 180.
If we assume start and end is the start and end of current year then all you need is the date("z") to calculate the percentage.
Round the value to desired format and echo the percentage.
$today ="30/06/2018";
echo round(date("z", strtotime(str_replace("/", "-", $today)))/365*100,0) . "%";
// 49%
https://3v4l.org/EG6lt
I assume 365 days is enough accurate as a year.
You can use 365 + date("L") instead of only 365 in the code above and it will add one if it's a leap year.
Meaning:
echo round(date("z", strtotime(str_replace("/", "-", $today)))/(365 + date("L"))*100,0) . "%";

Related

PHP get date after one week and calculate the number of days left

I have a dynamic date, now what i want is that finding the date after exact one week, i have achieved that with the code below, but now i want that now many days are left for that week after date to come. i have got some sort of time stamp, but i don't know how to convert it to DAYS LEFT.
$weekDate = date( "d/m/Y", strtotime("19-05-2014") + 86400 * 7 );
echo $weekDate;// THATS PERFECT
////////////////////////////////////////////////////////////////
$future = strtotime( $weekDate ); //Future date.
$datediff = time() - $future;
$days = floor( ( ( $datediff / 24 ) / 60 ) / 60 ); //this is not perfect, returns some
sort of timestamp
I have tried other methods which are fine, but if week completes on 26, and today is 25th it gives me 0 days left, but it should say 1 day left. please help me.
In your $date_diff now is less than the future date thats why its zero. Inside strtotime() function, you can directly put a relative date inside. In this case, for one week you can use +1 week or +7 days. Consider this example:
$next_week = date('d/m/Y', strtotime('19-05-2014 +1 week')); // 26/05/2014
$next_week = strtotime('19-05-2014 +7 days');
$difference = $next_week - time(); // next weeks date minus todays date
$difference = date('j', $difference);
echo $difference . (($difference > 1) ? ' days ' : ' day ') . ' left';
// should output: 1 day left
Alright. I did something. Here's the code
$startDate = strtotime("19-05-2014");
$endDate = $startDate + 604800;
$diff = ($endDate - time()) / 60 / 60 / 24;
if ($diff < 1 && $diff > 0) {
$days = 1;
} else {
$days = floor($diff);
}
echo $days;
The problem you have with getting "1 day" if the date is tomorrow is the floor method. strtotime() gives you the time at 0 a.m. if you don't set it by your own. Because of that the difference between now and tomorrow is less than 1 which is 0 if you floor that. I created an if-clause for that.
But that will give you "1 day" for today and "1 day" for yesterday (last 2 days before the final date). If you want that better, you have to specify time in your initial date (19-05-2014).
Use DateTime for date and time calculations.
$weekDate = new \DateTime('+ 1 week');
$future = new \DateTime('+ 3 days');
$daysLeft = $weekDate->diff($future)->days;
echo $daysLeft; //4
See it working.
Reference http://php.net/datetime

php how to to do operation on date

I have problem when i want calculate date. Simple Example:
I have 2013-09-01 is start date and I have 30day per month. My work i need alert tell to my user in 10 day before end month(it's mean on 2013-09-20i must alert message it's 10day more for end of this month). So every one have any idea for help to calculate it. becuese i like can't (+, -, *,/) on date. Now i am some data like
<?php
date_default_timezone_set('Asia/Phnom_Penh');
$current = time();
$start = 1380188957;
echo 'Start date: '. date('Y-m-d', $start) ."\n";
echo '<br/>';
$repeat = 30;
$enddate = time() + ($repeat * 24 * 60 * 60);
echo 'end date: '. date('Y-m-d', $enddate) ."\n";
Thanks in advent for helping.
Not every month has 31 days, you can get the number of days in any month by using the t option for the string format param in php's date() function.
// Current time as unix timestamp
$now = time();
// Number of days in current month
$days_this_month = date("t", time());
// Last day of the current month as a unix timestamp;
$end_of_month = strtotime(date("Y-m-t", time()));
// Ten days before the end of the month as a unix timestamp
$ten_days = strtotime('-10 days', $end_of_month);
Now we can do a check to see if it is 10 days before the end of the month:
if($now > $ten_days) {
// Do something
}
$start = 1380188957;
$enddate = time() + ($repeat * 24 * 60 * 60);
That's your own code. Using that we can easily compute 10 days before end date
$alert=$enddate-864000; // That's 10 days
$alertdate=date('Y-m-d', $alert);

Get duration between date time formats

how to get duration between start_date and end_date in hrs min sec format in php?
$start_date=2012-03-23 11:58:14 and $end_date=2012-03-24 11:54:29
Use DateTime class:
$start_date = new DateTime('2012-03-23 11:58:14');
$end_date = new DateTime('2012-03-24 11:54:29');
$dd = date_diff($end_date, $start_date);
To get hours use $dd->h, minutes - $dd->i, seconds - $dd->s.
echo "Hours = $dd->h, Minutes = $dd->i, Seconds = $dd->s";
I would
$start_time = strtotime($start_date);
$end_time = strtotime($end_date);
$difference = $end_time - $start_time;
echo date('H:i:s', $difference);
EDIT
I made an error in assuming that the time difference would be less then a day, so if the time difference is greater then a day, you will only see the Hours:minuetes:seconds, which is probably not what you want (if it is ignore this)
So I would now
$seconds = $difference % 60; //seconds
$difference = floor($difference / 60);
$min = $difference % 60; // min
$difference = floor($difference / 60);
$hours = $difference; //hours
echo "$hours : $min : $seconds";
Sorry for the correction
This function will help you
function datediff($interval, $datefrom, $dateto, $using_timestamps = false) {
/*
$interval can be:
yyyy - Number of full years
q - Number of full quarters
m - Number of full months
y - Difference between day numbers
(eg 1st Jan 2004 is "1", the first day. 2nd Feb 2003 is "33". The datediff is "-32".)
d - Number of full days
w - Number of full weekdays
ww - Number of full weeks
h - Number of full hours
n - Number of full minutes
s - Number of full seconds (default)
*/
http://php.net/manual/en/function.date-diff.php
format those string to date
transform those date to milliseconds
do endate - stardate
from the result calculate the h:mm:ss
See it working here: http://codepad.viper-7.com/FPuOks
$start_date="2012-03-22 11:58:14";
$end_date="2012-03-24 11:54:29";
$start_time = strtotime($start_date);
$end_time = strtotime($end_date);
$difference = $end_time - $start_time;
echo sprintf("%02d%s%02d%s%02d", floor($difference/3600), ':', ($difference/60)%60, ':', $difference%60); // outputs 47:56:15

Calculate total hours between 2 time stamps

I have two variables:
$start_time = '9:36';
$end_time = '12:47';
How would i calculate the amount of hours between the two times and store them in a variable like this:
$total_hours = 3;
I have read that you need to convert the times first. Also there will be no need for date as this will all be on the same day.
Any help would be appreciated
if you only need to calculate the hours difference you could use the datetime class especifically the function date_parse_from_format where you just need to provide the format as seed and then what you need to parse give that calculate the difference
Edit 1
you could do something with less overhead:
$start_time = '9:36';
$end_time = '12:47';
$today = date('Y-d-m');
$start = strtotime($today . ' ' . $start_time);
$end = strtotime($today . ' ' . $end_time);
$diff = floor(($end - $start) / 3600);
// or if you don't need the exact hours
$diff = ($end - $start) / 3600;
Convert time string tor timestamp: strftime
Take the difference, and
a. Use date to get the hours (H) value
b. Divide with 3600 and round as much digit as you
need
$total_hours = (int)date('G', abs(strtotime($time2)-strtotime($time1)));
See below
$start_time = '9:36';
$end_time = '12:47';
$v = strtotime($end_time) - strtotime($start_time);
echo date("h:i", $v);
Outputs
03:11
http://php.net/manual/en/function.strtotime.php and http://php.net/manual/en/function.date.php
This solves your problem:
$start = explode(':', $start_time);
$end = explode(':', $end_time);
$total_hours = $end[0] - $start[0] - ($end[1] < $start[1]);
See this codepad for a proof.
This solution assumes both hours are from the same day.
Why are you guys making it complicated? It can be done in a one-liner code:
abs((strtotime("11:00 AM") - strtotime("12:00 PM")) / 3600)
Result:
1
Please note that this assumes that both time are in the same day, although it will still work if both are from different dates.

How do I find the hour difference between two dates in PHP?

I have two dates, formated like "Y-m-d H:i:s". I need to compare these two dates and figure out the hour difference.
You can convert them to timestamps and go from there:
$hourdiff = round((strtotime($time1) - strtotime($time2))/3600, 1);
Dividing by 3600 because there are 3600 seconds in one hour and using round() to avoid having a lot of decimal places.
You can use DateTime class also -
$d1= new DateTime("06-08-2015 01:33:26pm"); // first date
$d2= new DateTime("06-07-2015 10:33:26am"); // second date
$interval= $d1->diff($d2); // get difference between two dates
echo ($interval->days * 24) + $interval->h; // convert days to hours and add hours from difference
As an addition to accepted answer I would like to remind that \DateTime::diff is available!
$f = 'Y-m-d H:i:s';
$d1 = \DateTime::createFromFormat($date1, $f);
$d2 = \DateTime::createFromFormat($date2, $f);
/**
* #var \DateInterval $diff
*/
$diff = $d2->diff($d1);
$hours = $diff->h + ($diff->days * 24); // + ($diff->m > 30 ? 1 : 0) to be more precise
\DateInterval documentation.
$seconds = strtotime($date2) - strtotime($date1);
$hours = $seconds / 60 / 60;
You can try this :
$time1 = new DateTime('06:56:58');
$time2 = new DateTime('15:35:00');
$time_diff = $time1->diff($time2);
echo $time_diff->h.' hours';
echo $time_diff->i.' minutes';
echo $time_diff->s.' seconds';
Output:
8 hours 38 minutes 2 seconds
The problem is that using these values the result is 167 and it should be 168:
$date1 = "2014-03-07 05:49:23";
$date2 = "2014-03-14 05:49:23";
$seconds = strtotime($date2) - strtotime($date1);
$hours = $seconds / 60 / 60;
$date1 = date_create('2016-12-12 09:00:00');
$date2 = date_create('2016-12-12 11:00:00');
$diff = date_diff($date1,$date2);
$hour = $diff->h;
This is because of day time saving.
Daylight Saving Time (United States) 2014 began at 2:00 AM on
Sunday, March 9.
You lose one hour during the period from $date1 = "2014-03-07 05:49:23" to
$date2 = "2014-03-14 05:49:23";
You can try this:
$dayinpass = "2016-09-23 20:09:12";
$today = time();
$dayinpass= strtotime($dayinpass);
echo round(abs($today-$dayinpass)/60/60);
You can use strtotime() to parse your strings and do the difference between the two of them.
Resources :
php.net - strtotime()

Categories