calculating negative and positive hours - php

I have durations in %RH:i:s format (like +00:00:00 or -00:00:00) and I want to add or subtract them (with the negative) and not in 24 hours
Ex :
1/ (09:30:15+(-10:00:00)) = -01:30:15.
2/ 22:00:00 + 03:00:00 = 25:00:00 (not 01:00:00 +1day)
Any idea ? Thanks in advance !
EDIT:
Finally did it. Don't know if it's the real right way to do it but it works pretty well. Found it by the help of another function found on a forum.
function calc_hours($hour1,$hour2){
$si1 = $hour1[0]; $si2 = $hour2[0];
$hour1 = substr($hour1,1,8);
$hour2 = substr($hour2,1,8);
$secondes1=intval($si1.heure_to_secondes($hour1));
$secondes2=intval($si2.heure_to_secondes($hour2));
$somme=intval($secondes1+$secondes2);
//transfo en h:i:s
$s= ($somme % 60);
$m1= (($somme-$s) / 60);
$m= ($m1 % 60);
$h= (($m1-$m) / 60);
if($somme > 0) { $sif = '+'; }
$resultat=sprintf("%02d", $h).":".sprintf("%02d", abs($m)).":".sprintf("%02d", abs($s))."";
return $sif.$resultat;
}
function heure_to_secondes($heure){
$array_heure=explode(":",$heure);
$secondes=3600*$array_heure[0]+60*$array_heure[1]+$array_heure[2];
return $secondes;
}
Call it like : calc_hours('+27:45:16','-02:35:12');

Finally did it. Don't know if it's the real right way to do it but it works pretty well. Found it by the help of another function found on a forum.
function calc_hours($hour1,$hour2){
$si1 = $hour1[0]; $si2 = $hour2[0];
$hour1 = substr($hour1,1,8);
$hour2 = substr($hour2,1,8);
$secondes1=intval($si1.heure_to_secondes($hour1));
$secondes2=intval($si2.heure_to_secondes($hour2));
$somme=intval($secondes1+$secondes2);
//transfo en h:i:s
$s= ($somme % 60);
$m1= (($somme-$s) / 60);
$m= ($m1 % 60);
$h= (($m1-$m) / 60);
if($somme > 0) { $sif = '+'; }
$resultat=sprintf("%02d", $h).":".sprintf("%02d", abs($m)).":".sprintf("%02d", abs($s))."";
return $sif.$resultat;
}
function heure_to_secondes($heure){
$array_heure=explode(":",$heure);
$secondes=3600*$array_heure[0]+60*$array_heure[1]+$array_heure[2];
return $secondes;
}
Call it like : calc_hours('+27:45:16','-02:35:12');

Related

Undefined offset (in function)

I get this error in my dates function
when my in panel this code calls the function fecha,only when it calls the date it throws the error, the status and the amount, if it appears to me.
<h1>Viendo compra de <span style="color:#08f"><?=$nombre?></span></h1><br>
Fecha: <?=fecha($r['fecha'])?><br>
Monto: <?=number_format($r['monto'])?> <?=$divisa?><br>
Estado: <?=estado($r['estado'])?><br>
here is the function
<?php
function fecha($fecha){
$e = explode("-",$fecha);
$year = $e[0];
$month = $e[1];
$e2 = explode(" ",$e[2]);
$day = $e2[0];
$time = $e2[1];
$e3 = explode(":",$time);
$hour = $e3[0];
$mins = $e3[1];
return $day."/".$month."/".$year." ".$hour.":".$mins;
}
?>
You need not to reinvent bicycle, just use PHP built in functions:
<?php
function fetcha($originalDate) {
return date("d/m/Y H:i", strtotime($originalDate));
}
echo fetcha('2020-12-06 10:11:12');
Test PHP code here

Get time data from DB - Laravel

I want to give an alert when a condition is met in a day time, right now I get the hours statically
$hour1 = strtotime ("09:00");
$hour2 = strtotime ("01:00");
but I want to get the established schedule from the DB
$hour1 = strtotime ("09:00");
$hour2 = strtotime ("01:00");
if ($hour1 > $hour2) {
Session::flash('message', 'ABIERTO!');
Session::flash('', '');
}
elseif ($hour1 < $hour2 ) {
Session::flash('message', 'SHOP CLOSED!');
Session::flash('alert-class', 'alert-danger');
}
I already created the model on table status
help pls
You can try like this
$hour1 = DateTime::createFromFormat('H:i', $status->open);
$hour2 = DateTime::createFromFormat('H:i', $status->closed);
OR just simply
$hour1 = new DateTime($status->open);
$hour2 = new DateTime($status->closed);
Then just make conditional
if ($hour1 > $hour2)
// what to do

How to calculate NPER in PHP

I can't figure out how to calculate NPER in php.
I did not find any article in google.
I'm very weak in math becouse of it i'm asking for help.
This is what i did so far :(
public function Nper($interest, $payment, $loan){
$nperC = Log10($payment/($payment+$loan+$interest))/Log10(1+$interest);
return $nperC;
}
if(isset($_POST['NperSubmit'])){
$calc = new CalculatorModel();
$months = $calc->Nper($_POST['interest'], $_POST['payment'], $_POST['loan']);
echo round($months,2);
}
Working code (From Tijo John answer)
public function Nper($interest, $payment, $loan){
$interest = $interest / 1200;
$nperC = Log10 ($payment/ ($payment- $loan * $interest)) / Log10(1 + $interest);
return $nperC;
}
$calc = new CalculatorModel();
$months = $calc->Nper($_POST['interest'], $_POST['payment'], $_POST['loan']);
echo round($months,2);
Thanks :))
I think you should have change the formula as follows
Log10 ($payment/ ($payment- $loan * $interest)) / Log10(1 + $interest)

Youtube playlist all videos duration show in php

i want to equal youtube playlist all videos time from this link http://gdata.youtube.com/feeds/api/playlists/PLCK7NnIZXn7gGU5wDy9iKOK6T2fwtGL6l. here have time code like this time='00:05:11.500' .. i want to get all videos time from php then its show like this from php
show it like this : 2:10:50 (2=hours,10=minutes,50=seconds)
i want to variable from php for like this one. plzz help for this post thanks. i tried to do that.. but i can do this.. if someone can plz help me.. if have 4 videos, want to equal all videos time and then want to show all duration from php only
Ok, here's an answer that solves the problem assuming you have no code whatsoever, and no intention of
trying do experiment yourself.
You will probably not be able to use this for anything else than the exact problem described:
adding all the durations of this feed together and displaying it as hours:minutes:seconds
<?php
$total_seconds = 0;
$dom = new DOMDocument();
$dom->loadXML(file_get_contents('http://gdata.youtube.com/feeds/api/playlists/PLCK7NnIZXn7gGU5wDy9iKOK6T2fwtGL6l'));
$xpath = new DOMXPath($dom);
foreach ($xpath->query('//yt:duration/#seconds') as $duration) {
$total_seconds += (int) $duration->value;
}
Then you display $total_seconds in your format. Here's two options:
assuming that hours will never be larger than 24
echo gmdate("H:i:s", $total_seconds);
allowing total time to be larger than 24 hours
echo (int) ($total_seconds / 3600) . ':' . (int) ($total_seconds / 60) % 60 . ':' . $total_seconds % 60;
Keep in mind: This code does exactly ZERO error checking. Things that can go wrong:
The PHP configuration may not allow http stream wrapper
The PHP build might not have Dom enabled
The XML feed may be unavailable
The XML feed might not contain any entries
EDIT:
I took a closer look at the feed, and it seems the "time" entries are just pointers for the thumbnails. The actual duration for a video is set in seconds <yt:duration seconds='667'/> so you could just add them together as integers and then use the DateTime class to convert to whatever your format is. Example here.
END EDIT
First of all, to get all the times, you could need an atom feed reader in PHP. There are plenty out there. Do not try to parse the XML, ATOM is a well known standard that should be easily used (if you really only want the times, you could go with an xpath query).
Now that you have all the times at your disposal, you need a way to add them up easily, preferably without messing with nested loops and if-statements.
Here's a class that represents a single time entry for a single video:
final class Duration
{
private $hours;
private $minutes;
private $seconds;
private $centis;
/* we don't want any Durations not created with a create function */
private function __construct() {}
public static function fromString($input = '00:00:00.000') {
$values = self::valuesFromString($input);
return self::fromValues($values['hours'], $values['minutes'], $values['seconds'], $values['centis']);
}
public function addString($string) {
$duration = self::fromString($string);
return $this->addDuration($duration);
}
public function addDuration(Duration $duration) {
// add the durations, and return a new duration;
$values = self::valuesFromString((string) $duration);
// adding logic here
$centis = $values['centis'] + $this->centis;
$this->fixValue($centis, 1000, $values['seconds']);
$seconds = $values['seconds'] + $this->seconds;
$this->fixValue($seconds, 60, $values['minutes']);
$minutes = $values['minutes'] + $this->minutes;
$this->fixValue($minutes, 60, $values['hours']);
$hours = $values['hours'] + $this->hours;
return self::fromValues($hours, $minutes, $seconds, $centis);
}
public function __toString() {
return str_pad($this->hours,2,'0',STR_PAD_LEFT) . ':'
. str_pad($this->minutes,2,'0',STR_PAD_LEFT) . ':'
. str_pad($this->seconds,2,'0',STR_PAD_LEFT) . '.'
. str_pad($this->centis,3,'0',STR_PAD_LEFT);
}
public function toValues() {
return self::valuesFromString($this);
}
private static function valuesFromString($input) {
if (1 !== preg_match('/(?<hours>[0-9]{2}):(?<minutes>([0-5]{1}[0-9]{1})):(?<seconds>[0-5]{1}[0-9]{1}).(?<centis>[0-9]{3})/', $input, $matches)) {
throw new InvalidArgumentException('Invalid input string (should be 01:00:00.000): ' . $input);
}
return array(
'hours' => (int) $matches['hours'],
'minutes' => (int) $matches['minutes'],
'seconds' => (int) $matches['seconds'],
'centis' => (int) $matches['centis']
);
}
private static function fromValues($hours = 0, $minutes = 0, $seconds = 0, $centis = 0) {
$duration = new Duration();
$duration->hours = $hours;
$duration->minutes = $minutes;
$duration->seconds = $seconds;
$duration->centis = $centis;
return $duration;
}
private function fixValue(&$input, $max, &$nextUp) {
if ($input >= $max) {
$input -= $max;
$nextUp += 1;
}
}
}
You can create a new Duration only by calling the static factory fromString(), and that accepts only strings in the form "00:00:00.000" (hours:minutes:seconds.milliseconds):
$duration = Duration::fromString('00:04:16.250');
Next, you can add another string or an actual duration object, to create a new Duration:
$newDuration = $duration->addString('00:04:16.250');
$newDuration = $duration->addDuration($duration);
The Duration object will output it's own duration string in the format '00:00:00.000':
echo $duration;
// Gives
00:04:16.250
Or, if you're interested in the separate values, you can get them like so:
print_r($duration->toValues());
// Gives
Array
(
[hours] => 0
[minutes] => 4
[seconds] => 16
[milliseconds] => 250
)
Final example for using this in a loop to get the total video time:
$allTimes = array(
'00:30:05:250',
'01:24:38:250',
'00:07:01:750'
);
$d = Duration::fromString();
foreach ($allTimes as $time) {
$d = $d->addString($time);
}
echo $d . "\n";
print_r($d->toValues());
// Gives
02:01:45.250
Array
(
[hours] => 2
[minutes] => 1
[seconds] => 45
[milliseconds] => 250
)
For questions on why I used a final class with private constructor:
I wrote this as an exercise for myself, following Mathias Veraes's blog post on "named constructors".
Also, I couldn't resist adding his "TestFrameworkInATweet" as well:
function it($m,$p){echo ($p?'✔︎':'✘')." It $m\n"; if(!$p){$GLOBALS['f']=1;}}function done(){if(#$GLOBALS['f'])die(1);}
function throws($exp,Closure $cb){try{$cb();}catch(Exception $e){return $e instanceof $exp;}return false;}
it('should be an empty duration from string', Duration::fromString() == '00:00:00.000');
it('should throw an exception with invalid input string', throws("InvalidArgumentException", function () { Duration::fromString('invalid'); }));
it('should throw an exception with invalid seconds input string', throws("InvalidArgumentException", function () { Duration::fromString('00:00:61:000'); }));
it('should throw an exception with invalid minutes input string', throws("InvalidArgumentException", function () { Duration::fromString('00:61:00:000'); }));
it('should add milliseconds to seconds', Duration::fromString('00:00:00.999')->addString('00:00:00.002') == Duration::fromString('00:00:01.001'));
it('should add seconds to minutes', Duration::fromString('00:00:59.000')->addString('00:00:02.000') == Duration::fromString('00:01:01.000'));
it('should add minutes to hours', Duration::fromString('00:59:00.000')->addString('00:02:00.000') == Duration::fromString('01:01:00.000'));
it('should add all levels up', Duration::fromString('00:59:59.999')->addString('00:01:01.002') == Duration::fromString('01:01:01.001'));
$duration = Duration::fromString('00:00:01.500');
it('should add a Duration', $duration->addDuration($duration) == '00:00:03.000');

Php Date not working on the server

for some reason the Php date isn't working on the server.
Here is the function for displaying the tip of the day. I am using the codeigniter framework. In the function below i am trying to print the day of year ($doy). When i go to the url and try to access the tip function it shows a blank page. The day of year is not printed.
public function tip(){
$idCount = $this->db->query('SELECT Count(*) AS COUNT FROM clickmag_tip')->result();
$total = $idCount[0]->COUNT;
$time = time();
$doy = mdate('%z', $time);
echo $doy;
//$day_of_year = date('z',time());
//$doyear = date("z") + 1;
//echo $doyear;
$s = mktime(date("G") + 1);
print date("Y/m/d h:i:s a", $s);
if($total > 0){
$offset = $doy % $total ;
}
$data = $this->db->query('SELECT * FROM table_tip LIMIT 1 OFFSET '. $offset);
header('Content-type: text/json');
header('Content-type: application/json');
echo json_encode($data->result());
}
What do you think is the problem? I talked to the server people but they also don't know.
How can i solve this?
Thanks in advance!
You must output all headers before outputting anything.
You have both:
echo $doy;
AND
print date("Y/m/d h:i:s a", $s);
Before
header('Content-type: text/json');
header('Content-type: application/json');
That is what's causing the blank page.

Categories