How to calculate percentage with date - php

How can I do the percent calculation with dates since I have the following code
$date_today = date("Y-m-d");
$date_db = $row['date_final'];
$date1 = new DateTime($date_today);
$date2 = new DateTime($date_db);
$diff = $date1->diff($date2);
$result = $diff->format("%a");
The result of my variable $result and the total days of difference of the given date1 and date2 as I do the percent with them with that result of the variable $result

Here's some psuedo code, which may or may not help.
$date_start = 20160101
$date_today = 20160315 // 75 days have passed
$date_end = 20161231 // 366 days in total
Calculate the difference between $date_start and $date_today, which should give you 75. I'll call that $date_so_far.
What you are missing as far as getting a percentage is the TOTAL number of days in the calculation. Get that by doing a difference between $date_end and $date_start. I'll call that $date_range.
$date_pct = $date_so_far / $date_range
// should give you roughly .21, which represents that you are about 20% into your range.
Is that what you are seeking?

Related

Efficiently check if exactly 2 days passed from given datetime in my case

I have following code that add 2 days to a given date.
$myDate = 2018-07-28 11:00:00; // the date is picked from db
$penaltyDays = 2;
$date1 = new DateTime($myDate);
$date1->add(new DateInterval("P{$penaltyDays}D")); // add N days
$now = new DateTime();
$interval = $date1->diff($now); // get difference
$days = $interval->d; // difference in days
I want value of $days must be 0 after passing exactly 48 hours. If 3 days are passed the value of $days should be -1.
I will also appreciate if someone tell me efficient/proper way to get the result.
To make an efficient code according to your specification then I would rather use strtotime than DateTime.
This code checks if the current time is larger than the database time + two (or three) days in seconds.
$myDate = "2018-07-28 11:00:00";
$unix = strtotime($myDate);
if(time() > ($unix + 86400*3)){
$days = -1;
}else if(time() > ($unix + 86400*2)){
$days = 0;
}else{
$days = "something else";
}
Echo $days;
https://3v4l.org/d6Q15

DateTime diff returning wrong value

I would like to return the number of days between NOW and some datetime using DateTime object. My dates are:
$now = "2018-03-08 14:00:00";
$last = "2018-02-06 20:00:00";
And I do it like this:
$now = new DateTime();
$last_dt = new DateTime($last);
$difference = $last_dt->diff($now);
$difference->format('%d');
$num_of_days = $difference->d;
For some weird reason, the value of $num_of_days is 1 (instead of like 30)
Anybody knows why please?
Thank you
You need to use DateInterval::$days to get the total in days.
DateInterval::$d is just the number of days but in "grouping form", i.e. 32 days difference will return 2 for DateInterval::$d and 1 for DateInterval::$m.
$last = "2018-04-10 20:00:00";
$now = new DateTime();
$last_dt = new DateTime($last);
$difference = $last_dt->diff($now);
echo "Difference: ".$difference->m." months and ".$difference->d." days, or ".$difference->days." days in total";
Result
Difference: 1 months and 2 days, or 33 days in total
Demo
You can see more in the manual

Time To Percent Using PHP

This may sound like a dumb question, but how can I convert the time between two dates to a percent?
I am using this Jquery plugin: http://tinacious.github.io/goalProgress/
The script on page that calculates the percent is:
$('#timerGoal').goalProgress({
goalAmount: 100,
currentAmount: 40,
textBefore: '',
textAfter: '% Completed.'
});
Where it says goalAmount: I'd like that to remain at 100, but where it says currentAmount: 40, I'd somehow like to find the difference in percentage between two days, I know I'd have to set a start date, current date, and end date to find a percentage.
I'm certain part of the code would have to be:
$startDate = '01/01/2015 12:00:00';
$currentDate = date('d/M/Y H:i:s');
$endDate = '02/15/2015 12:00:00';
Finding the difference in two dates is fairly easy, but it's the third date thing I cannot grasp, especially to make it a percentage.
Any ideas?
I was thinking something along the lines of:
[Taken from: How to find the difference in days between two dates ]
$daylen = 60*60*24;
$date1 = '2010-03-29';
$date2 = '2009-07-16';
echo (strtotime($date1)-strtotime($date2))/$daylen;
But everything I read on is two dates not three.
Here is what I've come up with.
It's not calculating percentages yet, but it's something to possibly go off of:
$startDate = '08/01/2015 12:00:00';
$currentDate = date('d/M/Y H:i:s');
$endDate = '09/01/2015 12:00:00';
$startDate =str_replace(array(':', '/', ' '), '', $startDate);
$currentDate =str_replace(array(':', '/', ' '), '', $currentDate);
$endDate =str_replace(array(':', '/', ''), ' ', $endDate);
$mainPercent = $endDate - $startDate;
$actualPercent = $endDate - $currentDate;
$displayPercent = $actualPercent/$mainPercent * 100;
echo $displayPercent;
With todays date being 08/07/2015 I am getting 901.2015119993 which is obviously not a percent, but it's a start.
Working Solution:
$startDate = strtotime('08/01/2015 12:00:00');
$currentDate = time(date('d/M/Y H:i:s'));
$endDate = strtotime('09/15/2015 12:00:00');
$dateDivideBy = $endDate - $startDate;
$dateDivide = $currentDate - $startDate;
$divideProduct = $dateDivide / $dateDivideBy;
$datePercent = round($divideProduct * 100);
echo $datePercent;
With this working code and todays date being 08/07/2015 the value of $datePercent is 14.
The difference between two times, by itself, really can't be converted to a percentage. It's just a period of time. In order to figure out what percentage is complete, you would need to know how long the entire goal is supposed to take (an estimated time, I assume.) Then you can figure out the percentage like this:
ElapsedTime / TotalTime * 100
The total time would be End Date - Start Date, and the elapsed time would be now - start date.
Rather than using string functions to manipulate the dates, it would be better to use DateTime functions.
$startDate = '08/01/2015 12:00:00';
$endDate = '09/01/2015 12:00:00';
$startDate = new DateTime($startDate);
$currentDate = new DateTime(); // defaults to now
$endDate = new DateTime($endDate);
$totalTime = $endDate->diff($startDate)->format('%a');
$elapsedTime = $currentDate->diff($startDate)->format('%a');
// diff returns a DateInterval object; calling its format method
// with %a returns the number of days in the interval
$percent = ($elapsedTime / $totalTime) * 100;
I believe this is your desired outcome, where result is the resulting percent difference between start_actual_time and percent_time:
var percent_time= new Date("01/17/2013 11:20");
var start_actual_time = new Date("01/17/2012 11:20");
var end_actual_time = new Date("01/17/2014 11:20");
var range = end_actual_time - start_actual_time;
var diff = end_actual_time - percent_time;
var result = (diff / range)*100;
In this example, start_actual_time and percent_time are 40% different.

How to get exact average of n number of order in m number of months?

Example:
$difference = strtotime($to) - strtotime($from);
$months = ($difference / 86400 / 30 );
Problem: But this way I never get exact average. Because I can’t sure for 30 days there can be 31 and 28 days months also.
Even I tried to divide by 12 month average but that also can’t work in every month selection cases
read first and
change according to ur own
You can get number of days for certain month in certain year using this function:
PHP Manual - cal_days_in_month
You can get number of days for whole year using, for example, this solution:
Finding the total number of days in year
Also, if you just want to get number of days for current month, you can use this:
date("t");
Are you after the number of months in a date range? If so, you could modify this previous answer to handle what you want:
PHP: Loop through all months in a date range?
To what I think you're after, you'd do something like this
$date_from = strtotime("2013-08-01");
$date_to = strtotime("2013-10-01");
$month_count = 0;
while ($date_from < $date_to) {
$date_from = strtotime('+1 month', $date_from);
$month_count++;
}
// month_count = number of months covered in the date range
Or, if you're just looking for the number of days in a date range, you could do something like this:
$date_from = strtotime("2013-08-01");
$date_to = strtotime("2013-08-28");
$diff = $date_to - $date_from;
$days_in_range = floor($diff / (60*60*24));
//days_in_range = 27
Not entirely sure what you're after from your question.

How to assign price to each date after calculating difference between dates? (date_diff)

i am using the following code(based on this http://goo.gl/5HhSx) to calculate the difference between dates:
<?php
$date1 = '2012-03-29';
$date2 = '2012-04-02';
$datetime1 = date_create($date1);
$datetime2 = date_create($date2);
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%a days');
?>
The difference is 4 days.March has a fixed price(30€/day) and April has another(40€/day).
Is there a way to sum the whole price? Three days until the end of march and another two from april? How can i add them correctly?
Any help would be appreciated. Thanks.
For your exact example this works:
$date1 = '2012-03-29';
$dateBoundary = substr($date1, 0, 8).date('t', strtotime($date1));
$date2 = '2012-04-02';
$marchPrice = 30;
$aprilPrice = 40;
$datetime1 = date_create($date1);
$datetime1Boundary = date_create($dateBoundary);
$datetime2 = date_create($date2);
$interval1 = date_diff($datetime1, $datetime1Boundary);
$interval2 = date_diff($datetime1Boundary, $datetime2);
$totalPrice = ($interval1->format('%d') * $marchPrice) + ($interval2->format('%d') * $aprilPrice);
echo number_format($totalPrice, 2);
You can of course extrapolate the idea for periods which span multiple months.
Extract the month out of the date like this:
SELECT MONTH('8/14/04') as "Month";
for each date between '2012-03-29' and '2012-04-02' and then update the table accordingly.
In case, you want to add up the sum then use a stored procedure -declare a variable 'sum' intitialized to zero and add by using switch cases like : CASE '04' then sum+=30 , CASE '03' then sum+=20. Or,you can use an aggregate function too in your procedure for calculating.
Brief logic on achieving the target result.
Keep an array of price list for the months,
find the difference of months between the dates.
In a loop for the month take the day difference from the last day for that month and multiply with the corresponding price from the array.
Inside the loop sum all this calculation into an total amount variable.
Refer the mktime() and Date() functions

Categories