Calculating percent of time remaining from two dates - php

So far im trying to get the percentage of time remaining between two dates so i can use a progress bar..
I have the following code i'm passing in two dates and doing the sum but i am getting an error. i'm not sure if this error is because of the date format if so i can change it.
<?
$start = '2015-11-03 14:05:15';
$end = '2015-11-03 18:05:15';
$current = '2015-11-03 16:12:15';
$completed = (($current - $start) / ($end - $start)) * 100;
?>
<? print $completed; ?>
I am getting the following error.
Warning: Division by zero

strtotime will take a date string and turn it into unix standard time as seconds.
<?
$start = strtotime('2015-11-03 14:05:15');
$end = strtotime('2015-11-03 18:05:15');
$current = strtotime('2015-11-03 16:12:15');
$completed = (($current - $start) / ($end - $start)) * 100;
?>
<? print $completed; ?>

I would recommend using the DateTime object over strtotime. DateTime allows you to specify the format that creates the timestamp, instead of relying on strtotime to magically figure it out. This makes it far more reliable.
For example:
<?php
$start = DateTime::createFromFormat('Y-m-d H:i:s', '2015-11-03 14:05:15');
$end = DateTime::createFromFormat('Y-m-d H:i:s', '2015-11-03 18:05:15');
$current = DateTime::createFromFormat('Y-m-d H:i:s', '2015-11-03 16:12:15');
$completed = (($current->getTimestamp() - $start->getTimestamp()) / ($end->getTimestamp() - $start->getTimestamp())) * 100;
echo $completed;
?>
Note: DateTime objects were introduced in PHP 5.3. Any older versions will not have DateTime. (and quite honestly, should be updated for many reasons)

You're using strings (basically, plain text)... So you can't calculate anything.
You should use timestamps for that (miliseconds since start of 1970)
http://php.net/manual/fr/function.strtotime.php
$start = strtotime('2015-11-03 14:05:15');
$end = strtotime('2015-11-03 18:05:15');
$current = strtotime('2015-11-03 16:12:15');

Those are strings. You can't subtract strings and expect things to work. What's happening is this:
$start = '2015-11-03 14:05:15';
$end = '2015-11-03 18:05:15';
Since you're doing -, PHP converts those strings to integers:
$new_start = (int)$start; // 2015
$new_end = (int)$end; // 2015
$new_end - $new_start -> 0
YOu need to strtotime() those values back into a unix timestamp, and then you CAN subtract those values, and get a difference in seconds.

Related

How to find range diff 'datetime' and 'time'?

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.

PHP converting strtotime into a microtime

I'm trying to find a way to make an strtotime with a provided datetime match up somewhat with a time generated from microtime(true).
I can't quite figure it out, I've tried dividing my strtotime by 1000 but this doesn't quite give me the right result, how can I match them up to be identical.
$time = strtotime('2022-04-06 09:00:00') / 1000;
$micro = microtime(true);
echo "$time - $micro";
output
1649260.8 - 1649233311.5081
You can do this just by adding a dot and zeros to your string :
$time = strtotime('2022-04-06 09:00:00');
$micro = microtime(true);
echo $time.".0000 - ".$micro;
Otherwise you can use the number_format function :
$time = strtotime('2022-04-06 09:00:00');
$timemicro = number_format($time, 4, '.', '');
$micro = microtime(true);
echo $timemicro." - ".$micro;
These are the simplest solutions I have found :)

A non well formed numeric value encountered in ...on Line 171

We keep getting the above error. Have tried adding a $start above 171 but same result. Here is the code :
/**
* Get all of the months since a certain date
*/
public static function getMonthsSinceDate($start) {
$key_month = date('MY', $start); (note this is Line 171)
$key = 'months_since_' . $key_month;
$months = CodonCache::read($key);
if ($months === false) {
if (!is_numeric($start)) {
$start = strtotime($start);
}
$end = date('Ym');
do {
# Get the months
$month = date('M Y', $start);
$months[$month] = $start; # Set the timestamp
$start = strtotime('+1 month +1 day', strtotime($month));
# Convert to YYYYMM to compare
$check = intval(date('Ym', $start));
} while ($check <= $end);
CodonCache::write($key, $months, 'long');
}
return $months;
}
/**
Wherever you are calling the function getMonthsSinceDate(); you are accidentally passing it something non numeric. It could be subtle like a number wrapped in quotes which would become a string, i.e
getMonthsSinceDate('111111')
PHP's date() expects to be given a date in an integer UNIX timestamp. If you are trying to pass a human-readable date as a string it will throw an error.
If you are, convert it to a timestamp using strtotime(), like this:
$start = strtotime( $start );

calculate difference betwen two datetime in php

I have 2 datetime , and I wanna to calculate difference in minutes :
$date_reservation=strtotime($_POST['date_reservation']);;
$dt = new DateTime();
$date_annulation = strtotime($dt->format('Y-m-d H:i:s'));
$attente = (round(abs($date_annulation - $date_reservation)/60)%60);
It only take the difference between minute without hours .
I've tried this function ( from php documentation )
$interval = $date_annulation->diff($date_reservation);
$years = $interval->format('%y');
$months = $interval->format('%m');
$days = $interval->format('%d');
But it dosn't work (error 500)
Your problem is that $date_annulation is not a DateTime object. Keep it simple using strtotime
<?php
$date_reservation = strtotime($_POST['date_reservation']);
$date_annulation = strtotime('now');
$diff_minutes = ($date_annulation - $date_reservation)/60;
echo $diff_minutes;
A response of 500 Internal Server Error means there is a problem in your PHP code. Check the server log files (Apache's error_log, PHP's php_errors.log) to find out the exact place (file and line) and the cause.
In the meantime, the code you copied from the documentation doesn't work because you tried to call a method of the DateTime class on a number (the value returned by strtotime(). It doesn't work this way.
It does work, however, if you use DateTime (and related) objects:
$date_reservation = new DateTime($_POST['date_reservation']);
$date_annulation = new DateTime('now');
$interval = $date_annulation->diff($date_reservation);
$years = $interval->format('%y');
$months = $interval->format('%m');
$days = $interval->format('%d');
If you are aware of the possible inaccuracies using this approach, you can just compare the Unix timestamps:
$date_reservation = strtotime('2016-05-20 13:30');
$date_annulation = strtotime('now');
$diff_minutes = round(abs($date_annulation - $date_reservation)/60, 0);
The only problem in your code is, that you mod 60 your minutes (%60). This of course gives you only the minutes above full hours.
Please note that strtotime interprets the datetime string using the time zone set on the machine running this code. You can set in your code using date_default_timezone_set().
See an example on ideone.com.
i give you code of time difference
<?php
//$datetime1=strtotime('Y-m-d','time to which difference obtained');
$current_time =strtotime(date("Y-m-d H:i:s"));
//$checkTimeEnd = strtotime('time to which difference obtained');
$checkTimeStart = strtotime('time to which difference obtained');
//echo $current_time;
$all = round((($current_time - $checkTimeStart) / 60),2);
//echo floor($all/(60*60*24));
$test = round($all/60,2);
$d = floor ($all / 1440);
$h = floor (($all - $d * 1440) / 60);
$m = $all - ($d * 1440) - ($h * 60);
?>
print $d for date $h for hours $m for minutes

How to compare two time in PHP

I had two times in the format like 7:30:00 and 22:30:00 stored in the variables $resttimefrom and $resttimeto respectively.
I want to check whether the current time is between these two values. I am checking this with the code
$time = date("G:i:s");
if ($time > $resttimefrom and $time < $resttimeto ){
$stat = "open";
} else {
$stat = "close";
}
But I am always getting the $stat as Close. What may cause that?
you can try using strtotime
$st_time = strtotime($resttimefrom);
$end_time = strtotime($resttimeto);
$cur_time = strtotime(now);
then check
if($st_time < $cur_time && $end_time > $cur_time)
{
echo "WE ARE CLOSE NOW !!";
}
else{
echo "WE ARE OPEN NOW !!";
}
i hope this may help you..
A simple yet smart way to do this is to remove the ':' from your dates.
$resttimefrom = 73000;
$resttimeto = 223000;
$currentTime = (int) date('Gis');
if ($currentTime > $resttimefrom && $currentTime < $resttimeto )
{
$stat="open";
}
else
{
$stat="close";
}
$today = date("m-d-y ");
$now = date("m-d-y G:i:s");
if (strtotime($today . $resttimefrom) < $now && $now > strtotime($today . $resttimeto)) {
$stat = 'open';
else
$stat = 'close
Try reformatting them into something that you can compare like that. For example, numbers:
$resttimefrom = mktime(7,30,0);
$resttimeto = mktime(22,30,0);
$time = mktime(date('H'),date('i'),date('s'));
You are comparing strings.
Convert the Time Strings to timestamps with strtotime().
Then compare against time().
Just convert your dates to a Unix Timestamp, compare them, you have your results! It might look something like this:
$time =date("G:i:s");
$time1 = strtotime($time);
$resttimefrom1 = strtotime($resttimefrom );
$resttimeto1 = strtotime($resttimeto );
if ($time1 >$resttimefrom and $time1 <$resttimeto)
{
$stat="open";
}
else
{
$stat="close";
}
The date function returns a string, so the comparison you're making would be a string comparison - so 7:30 would be more than 22:30
It would be much better to use mktime, which will return a Unix timestamp value (integer) so it would make for a better comparison
$currentTime = mktime();
$resttimefrom = mktime(hour,min,second);
http://php.net/mktime
The trick to manipulating and comparing dates and times in PHP is to store date/time values in an integer variable and to use the mktime(), date() and strtotime() functions. The integer repesentation of a date/time is the number of seconds since midnight, 1970-Jan-1, which is referred to as the 'epoch'. Once your date/time is in integer form you'll be able to efficiently compare it to other dates that are also in integer form.
Of course since you'll most likely be receiving date/time values from page requests and database select queries you'll need to convert your date/time string into an integer before you can do any comparison or arithmetic.
Assuming you are sure that the $resttimefrom and $resttimeto variables contain properly formatted time you can use the strtotime() function to convert your string time into an integer. strtotime() takes a string that is formatted as a date and converts it to the number of seconds since epoch.
$time_from = strtotime($resttimefrom);
$time_to = strtotime($resttimeto);
Side note: strtotime() always returns a full date in integer form. If your string doesn't have a date, only a time, strtotime() return today's date along with the time you gave in the string. This is not important to you, though, because the two dates returned by strtotime() will have the same date and comparing the two variables will have the desired effect of comparing the two times as the dates cancel each other out.
When you compare the two integers keep in mind that the earlier the date/time is, the smaller its integer value will be. So if you want to see if $time_from is earlier than $time_to, you would have this:
if ($time_from < $time_to)
{
// $time_from is ealier than $time_to
}
Now to compare a date/time with the current system date/time, just use mktime() with no parameters to represent the current date/time:
if ($time_from < mktime())
{
// $time_from is in the past
}
$firstTime = '1:07';
$secondTime = '3:01';
list($firstMinutes, $firstSeconds) = explode(':', $firstTime);
list($secondMinutes, $secondSeconds) = explode(':', $secondTime);
$firstSeconds += ($firstMinutes * 60);
$secondSeconds += ($secondMinutes * 60);
$difference = $secondSeconds - $firstSeconds;
$Time1 = date_parse($time);
$seconds1 = $Time1['hour'] * 3600 + $Time1['minute'] * 60 + $Time1['second'];
$Time2 = date_parse($current_time);
$seconds2 = Time2['hour'] * 3600 + Time2['minute'] * 60 + Time2['second'];
$actula_time = $seconds1 - $seconds2;
echo floor($actula_time / 3600) .":". floor(($actula_time / 60)%60) .":". $actula_time%60;
As Col. Shrapnel Said i am doing by converting all the time in to seconds and then compare it with current time's total seconds

Categories