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.
Related
I want to find a range combining both data, that data has datetime and time data types, but datetime must ignore the time.
<?php
function test_duration($start_date, $end_date, $start_time, $end_time) {
$timeInterval = '-';
if(!empty($start_time) && !empty($end_time)) {
$timeStart = new DateTime($start_date->format('Y-m-d').' '.$start_time->format('H:i:s'));
$timeEnd = new DateTime($end_date->format('Y-m-d').' '.$end_time->format('H:i:s'));
$timeInterval = $timeStart->diff($timeEnd)->format('%H:%I:%s');
}
return $timeInterval;
}
$start_date = '2022-09-15 01:01:01';
$end_date = '2022-09-15 02:02:02';
$start_time = '14:48:40';
$end_time = '14:48:45';
echo test_duration($start_date, $end_date, $start_time, $end_time);
?>
so the formula is like this:
range start ==> $start_date (just date) + $start_time
range end ==> $end_date (just date) + $end_time
range start - range end
From the code above it should produce a duration of 5 seconds.
Do you have any solution to fix my code above?
The time can easily be removed from the date with strstr. Then the pure date can be combined with the new time. strtotime is well suited when only seconds are to be determined.
$start_date = '2022-09-15 01:01:01';
$end_date = '2022-09-15 02:02:02';
$start_time = '14:48:40';
$end_time = '14:48:45';
$strStart = strstr($start_date, ' ', true).' '.$start_time;
$strEnd = strstr($end_date, ' ', true).' '.$end_time;
$seconds = strtotime($strEnd) - strtotime($strStart); // int(5)
Time is time, date is date, you shouldn't mix them, so let's say
$start_date = '2022-09-15';
$start_time = '13:00:00';
$end_date = '2022-09-15';
$end_time = '14:00:00';
print strtotime($end_date) + strtotime($end_time) - strtotime($start_date) - strtotime($start_time);
You'll get 3600 seconds
If you know the date is in a fixed format can't you just explode the string on the central space like this?
<?php
function test_duration($start_date, $end_date, $start_time, $end_time) {
$timeInterval = '-';
if(!empty($start_time) && !empty($end_time)) {
$startDateOnly=explode(' ',$start_date)[0];
$endDateOnly=explode(' ', $end_date)[0];
$timeStart = date_create_from_format('Y-m-d H:i:s', $startDateOnly." ".$start_time);
$timeEnd = date_create_from_format('Y-m-d H:i:s', $endDateOnly." ".$end_time);
$timeInterval = $timeStart->diff($timeEnd)->format('%h:%i:%s');
}
return $timeInterval;
}
$start_date = '2022-09-15 01:01:01';
$end_date = '2022-09-15 02:02:02';
$start_time = '14:48:40';
$end_time = '14:48:45';
echo test_duration($start_date, $end_date, $start_time, $end_time);
?>
Your start is quite good, the use of DateTime class is one of the ways to solve your issue. The idea here can be illustrated as follows:
create a DateTime object from the starting date and then alter its time (hours, minutes and seconds) based on the starting time you supply.
do the same thing as the first step but for the ending date so we'll create a DateTime object from the ending date and then alter its time based on the ending time.
return the difference between the two dates in seconds:
to do so we will get the timestamps from both dates
make a simple subtraction of th two timestamps
return the result. We may return the absolute value here to always get a positive number for the case when the starting date is greater than the ending date (not required but that can be seen as an improvement).
Here's a live demo too
$startDate = '2022-09-15 01:01:01';
$endDate = '2022-09-15 02:02:02';
$startTime = '14:48:40';
$endTime = '14:48:45';
function diffInSeconds($startDate, $endDate, $startTime, $endTime)
{
// create a DateTime object based on $startingDate and then alter the time to use the $startingTime instead
$startDate = (new DateTime($startDate))->setTime(
($startTime = explode(':', $startTime))[0],
$startTime[1],
$startTime[2]
);
// create a DateTime object based on $endingDate and then alter the time to use the $endingTime instead
$endDate = (new DateTime($endDate))->setTime(
($endTime = explode(':', $endTime))[0],
$endTime[1],
$endTime[2]
);
// return the difference in seconds which will always be positive thanks to the "abs" function
return abs($endDate->getTimestamp() - $startDate->getTimestamp());
}
// run...
echo diffInSeconds($startDate, $endDate, $startTime, $endTime); // prints: 5
the above is code somehow primitive, it doesn't have any checks on whether the date/times are correct or not also it expects the times to be in the following format "HH:MM:SS".
Anyway, i strongly recommend looking at more modern utilities, especially the Carbon library which makes working with dates and times in PHP a piece of cake.
Learn more about DateTime objects on php.net.
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?
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);
?>
I have two variables stored in my database containing the following data:
$date_published = 2012-05-04 00:00:00; //Straight from DB datetime field
$advert_duration = 15;
I want to show an advert for 15 days from the date it was published. To do so I need to work out the time difference.
I have read various places online about calculating time difference and have come up with the below code
In my attempt to work out the equation I can't seem to calculate the differences between $now - the date today, the $date_published and the $advert_duration. I can't get the correct result:
function days_left($date_published, $advert_duration){
$date = new DateTime($date_published);
$now = new DateTime();
$days_elapsed = $date->diff($now)->format("%d");
$days_left = $advert_duration - $days_elapsed;
return $days_left;
}
function getDaysLeft( $date, $duration )
{
// create $date and modify it by $duration
$date = new DateTime( $date );
$date->modify( sprintf( '+%d days', $duration ) );
// calculate the difference
$now = new DateTime();
$daysElapsed = (int) $now->diff( $date )->format( '%a' );
// set to negative value, if modified $date is before $now
if( $date < $now )
{
$daysElapsed = $daysElapsed * -1;
}
return $daysElapsed;
}
var_dump(
getDaysLeft( '2012-05-04 00:00:00', 15 ),
getDaysLeft( '2012-07-04 00:00:00', 15 )
);
If you're fetching your ad from the database, you can simply use a date function to calculate this :
WHERE DATE_SUB(CURDATE(),INTERVAL 15 DAY) >= date
Or you can do this in PHP (you'll get an UNIX timestamp) :
$date = strtotime('+15 days', strtotime($date_published));
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