I have a requirement where I need to extract 5 points from a Unix time stamp or PHP time stamp range.
For Example,
From 2014-06-26 07:53:26 to 2014-06-27 07:52:46.
I need five points from these two dates in exact or approximate intervals, to chart using pChart.
Currently My Code is
$diff = $mintime->diff($maxtime);
$range = max($timestamps) - min($timestamps);
$cnt = count($timestamps);
$temp = ceil($range * (20/100));
for($i=0;$i<$cnt;$i++)
{
if($i%($cnt/5) == 0)
$point[$i] = gmdate("Y-m-d H:i:s",min($timestamps) + $temp * ($i+1));
else
$point[$i] = null;
}
But My Code returns erratic values. I know the problem is with the temp variable. Help me solve this.
Thanks
Try this:
$from = '2014-06-26 07:53:26';
$to = '2014-06-27 07:52:46';
$diff_stamp = strtotime($to) - strtotime($from);
$range = range(strtotime($from), strtotime($to), $diff_stamp/4);
Here, $range is an array of timestamps. To convert each back to a date, you could use array_map:
$range = array_map(function($a){return date('Y-m-d H:i:s', $a);}, $range);
See Demo Updated
Resources:
strtotime(), range(), array_map()
$splitter=($timestamp1-$timestamp2);
$timestamp_between=array();
for($i=0;$i<5;$i++) $timestamp_between[]=$timestamp1+($i*$splitter);
print_r($timestamp_between);
Related
I need to show the difference between two times in PHP I use strtotime() function to convert my times to integer but my problem is the result not matched what I expected
<?php
$hour1 = '12:00:00';
$hour2 = '9:00:00';
$avg = strtotime($hour1) - strtotime($hour2);
$result = date('h:i:s', $avg); // result = 06:30:00 what I expected is 3:00:00
But the difference is 3:00:00 how to calculate this?
You can create DateTime instances and use diff function to get the difference between 2 times. You can then format them in hours,minutes and seconds.
<?php
$hour1 = '12:00:00';
$hour2 = '09:00:00';
$o1 = new DateTime($hour1);
$o2 = new DateTime($hour2);
$diff = $o1->diff($o2,true); // to make the difference to be always positive.
echo $diff->format('%H:%I:%S');
Demo: https://3v4l.org/X41pv
You can do that:
$hour1 = '12:00:00';
$hour2 = date('h', strtotime('9:00:00'));
$avg= date('h:i:s', strtotime($hour1. ' - '.$hour2.' hours') );
echo $avg; //3:00:00
I try to get an average of given dates but I failed when dates are from two different years. I need something like this
given dates:
2017-06-1
2017-06-3
2017-06-4
2017-06-3
2017-06-5
output : 2017-06-4
this is my code:
$total = 0;
foreach ($dates as $date) {
$total+= date('z', strtotime($date))+1;
}
$avg_day = $total/sizeof($dates);
$date = DateTime::createFromFormat('z Y', $avg_day . ' ' . date("Y"));
but my code is not working for
given dates:
2016-12-29
2016-12-31
2017-01-1
2017-01-5
2017-01-3
You can work with timestamp of the date and use avg() method of the Illuminate\Support\Collection
$dates = [
'2016-12-29', '2016-12-31', '2017-01-1', '2017-01-5', '2017-01-3'
];
$dateCollection = collect();
foreach($dates as $date){
$dateCollection->push((new \DateTime($date))->getTimestamp());
}
$averageTimestamp = $dateCollection->avg(); //timestamp value
$averageDate = date('Y-m-d', $average);
Or using Carbon package:
$dateCollection->push(Carbon::parse($date)->timestamp);
...
$averageDate = Carbon::createFromTimestamp($average)->toDateString();
Your code is not working for your base dates. The correct output for
2017-06-1 2017-06-3 2017-06-4 2017-06-3 2017-06-5
is
2017-06-03
According to OpenOffice calc, and overall logic (a date is represented by epoch number)
Check out this script
$dates = ['2017-06-1 ', '2017-06-3', '2017-06-4', '2017-06-3', '2017-06-5'];
$dates = array_map('strtotime', $dates);
$average = date('Y-m-d', array_sum($dates) / count($dates)); // 2017-06-03 (1496490480)
echo $average;
Keep simple tasks simple
I think you have problem with averaging year. So, You can do this to get average.
Just an algorithm:
Find smallest date among your dates at first as $smallest
Initiate a variable $total = 0;
Add difference of each date in days with smallest date.
Find average from total.
Add this total to smallest date.
Here, You have smallest as $smallest = '2016-12-29'
$total = 0;
$dates = ['2016-12-29', '2016-12-31', '2017-01-1', '2017-01-5', '2017-01-3'];
$smallest = min($dates);
$smallest = Carbon::parse($smallest);
foreach($dates as $date){
$d = Carbon::parse($date);
$total = $total+$smallest->diffInDays($d);
}
$average_day = $total/sizeof($dates);
$average_date = $smallest->addDays($average_day);
Hope, This might help you.
i tried most of what is available on stack overflow but none seem to work.
any way i am trying to compare two (date and time formats). and calculate whether their difference is within 5 seconds of each other
the first date is the current date:
$today = date("Y-m-d H:i:s");
the second date is taken from mysql database:
$result = mysql_query("SELECT * FROM BUS_DATA where BusRegID = 'bus'") or die(mysql_error());
$row = mysql_fetch_array($result);
$update_date = $row["update_date"];
the answer should be segmented into years , month , days , hours , minutes ,and seconds portions.
I am running PHP Version 5.3.3
Edit: most answers give result in time frame only , I want to check whether the date matches , then compare if the time of the day is within 5 seconds , than you guys in advance :)
Try this
function getTimes($t1, $t2)
{
$timeFirst = strtotime($t1);
$timeSecond = strtotime($t2);
$differenceInSeconds = $timeSecond - $timeFirst;
$h=0;
$m = floor($differenceInSeconds / 60);
$s = $differenceInSeconds % 60;
if ($m>=60)
{
$h = floor($m / 60);
$m = $m % 60;
}
$tim = $h.':'.$m.':'.$s;
return $tim;
}
it will return difference time in hours:min:sec
use strtotime, it's understands almost any date formats:
$timeDiff = abs(strtotime($today) - strtotime($update_date));
this gives you the difference between dates in seconds.
If you want to know whether it's within 5 seconds then use Timestamps, makes it into a simple int calculation.
$now = time();
$test = strtotime($update_date);
if($now - $test > 5) {
//NOT WITHIN 5 SECONDS
}
I want to calculate the number of years between two dates. One of them is retrieved from the database while the other is taken from user input in date format.
I used this code to get the date from the user:
$today = $_POST['to-day'];
$tomonth = $_POST['to-month'];
$toyaer = $_POST['to-year'];
$dateto = date("$toyaer-$tomonth-$today");
And here is how I calculated it with the one retrieved from the database,
$start = $leaveresult['date']; // i took from database
$end = strtotime($dateto);
$difference = abs($end - $start);
$years = floor($difference / (60*60*24*365));
The problem is that the result I get is always 0.
I tried different methods but all of them resulted with 0 and one of them resulted with a huge number.
This is untested but I think something like this will work:
$today = $_POST['to-day'];
$tomonth = $_POST['to-month'];
$toyear = $_POST['to-year'];
$dateto = "$toyear-$tomonth-$today";
$start = $leaveresult['date'];// i took from database
$end = strtotime($dateto);
$difference = abs($end - $start);
$years = floor($difference / (60*60*24*365));
I am assuming $leaveresult['date'] is unix timestamp
Also please note that I fixed the post variable names.
If the start date is not in unix timestamp then use
$start = strtotime($leaveresult['date']);// i took from database
The DateTime class simplifies all this by giving you a diff method. This will return a DateInterval object which you can get the values you're looking for.
Assuming $_POST looks like this:
$_POST = array(
'to-year' => 2010,
'to-month' => 8,
'to-day' => 22
);
And $leaveresult['date'] looks like this:
$leaveresult = array(
'date' => date('Y-m-d H:i:s', strtotime('-5 years')));
You can do something like this...
$input_date = new DateTime(sprintf("%d-%d-%d", $_POST['to-year'], $_POST['to-month'], $_POST['to-day']));
$database_date = new DateTime($leaveresult['date']);
$diff = $database_date->diff($input_date);
echo $diff->format('%r%y years') . PHP_EOL;
echo $diff->format('%r%m months') . PHP_EOL;
echo $diff->format('%r%d days') . PHP_EOL;
$years = $diff->y;
Which will yield
3 years
1 months
5 days
And $years will equal 3
you need in both cases a timestamp - the one you formatted ( as date object ) and the one you get from the database...
so I think you'r approach wasn't wrong, if your getting timestamps in both cases... but finally you've tried to round the number with floor... and of course this will result in 0, if it's less than a year.
test it without rounding first, and test your timestamps, maybe something is wrong there, too?
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