convert string array to integer php - php

Question:
How the best to convert $p=' "'.implode('","', $person).'"'; $p to an integer?
What I have:
I am trying to use an if statement telling $person == false;
$x['date']; is the timestamp in my database.
I have worked out the time difference, now I am trying to make the person disappear if post over 3 seconds.
so I used $t > 3 seconds then the $p == false;
The difficulty for my was the $t was implode so it a single string. I was trying to use preg_match, but I don't think this is a good idea.
I am trying to use $difference = settype($t, "integer"); but I am getting a boolean rather than a number.
$diff = array();
$person = array();
foreach($stmt as $x)
{
$person[] = $x['names']. $x['ages'];
$posts[] = $x['date'];
$timePosted = new DateTime($posts[] = $x['date']);
echo 'Time Posted : '. $timePosted ->format("d-m-Y H:i:s");
echo "</br>";
date_default_timezone_set('Europe/London');
$today = date('d-m-Y H:i:s');
echo 'Current time is : '. $today;
echo "</br>";
$today = new DateTime(date('d-m-Y H:i:s'));
$interval = $timePosted->diff($today);
"Difference " . $interval->d. " days ". $interval->h. " hours ".$interval->i." minutes ".$interval->s." seconds ";
echo "</br>";
$diff[] = $interval->h. " hours ".$interval->i." minutes ".$interval->s." seconds ";
$diff[] = $interval->s; //last array seconds
}
$p=' "'.implode('","', $person).'"';
echo $t= ' "'.implode('","', $diff).'"'."<br />";
$difference = settype($t, "integer");
echo gettype($difference);
echo "</br>";
if( $t >3){
$p == false;
}else{
echo "its okay, smaller than 3 seconds";
}

The problem is you're setting $difference = settype($t, "integer");
The settype function returns a boolean. The value $t should be set to an integer, so to test, use echo gettype($t); instead of echo gettype($difference);
also, you're using a comparison operator instead of the assignment in
if( $t >3){
$p == false;
it should be
if( $t >3){
$p = false;

Related

Best way to calculate time difference with the previous created_at - Laravel

I have a list of baby logs, and I've tried to auto calculate the time difference between the previous ones, subtract the feeding interval.
feedingInterval = 3h
Ex.
If I fed my baby at 5PM, and if I fed him again at 7:50 PM.
He's early 10 mins.
More than 3h, it's green(+) means the baby sleep well
Less than 3h, it's red(-) means the baby will feed early, and we shouldn't do too often.
I have this block of code
if($baby){
$dateTime = new \DateTime();
$date = $dateTime->format('Y-m-d');
if(Request::get('date') != null) {
$date = Request::get('date');
}
$yesterday = date('Y-m-d',strtotime("-1 days"));
$logFromYesterday = BabyLog::where('type', $type)->whereDate('created_at', $yesterday )->orderBy('created_at', 'desc')->where('babyId',$baby->id)->get()->first();
$babyLogs = BabyLog::where('type', $type)->whereDate('created_at', '=', $date)->orderBy('created_at', 'desc')->where('babyId',$baby->id)->get();
$logDetail = [];
$lastFeedStatus = 'n/a';
foreach ($babyLogs as $i => $feed) {
$id = $babyLogs[$i]->id;
$t1 = $babyLogs[$i]->updated_at;
if($i >= (count($babyLogs)-1)){
if($logFromYesterday){
$t2 = $logFromYesterday->updated_at;
} else {
$t2 = $date.' 00:00:00';
}
}else {
$t2 = $babyLogs[$i+1]->updated_at;
}
// dd($t1,$t2);//
$diffTime = abs(strtotime($t1) - strtotime($t2));
$diffTime = $diffTime / ( 60 * 60 );
if($type == 'feed'){
$diffTime = $diffTime - $baby->feedingInterval;
$diffTime = round($diffTime,2);
$diffTime = $diffTime*60;
$logDetailStatus = ($diffTime>0) ? "+" : "-";
$diffTime = $logDetailStatus.str_replace('-', '', $diffTime). "m ";
} else {
$diffTime = round($diffTime,2);
$diffTime = $diffTime*60;
$diffTime = str_replace('0', '',date('H\h', mktime(0,$diffTime))) . '';
}
$logDetail[$i]['id'] = $id;
$logDetail[$i]['msg'] = $diffTime;
if($i == 0){
$lastFeedStatus = $diffTime;
}
}
return $logDetail;
}
I want to round to minutes only.
Ex. 10.2 m --> 10 m
I tried
round($diffTime,2);
to
round($diffTime,1);
I got
Ex. 10.2 m --> 12 m
Try using number_format():
<?php
echo number_format("100.1234");
echo number_format("100.50");
echo number_format("100.890");
?>
Result will be:
100
101
101

How to know if a date/time string contain day or not in php?

I want to check if a date/time string contains a day or not.
I used the date_parse() function but it automatically adds day => 1 if it doesn't find any day.
So I couldn't know if a string contains a day or not.
For example
$date = "2021-02";
How to know if this string contains a day or not?
The DateTime::createFromFormat method tests well that the format is adhered to. Entries like "2019-02-" or "2019-xx-23" are also recognized as incorrect.
$date = "2021-02-x";
$dateTime = DateTime::createFromFormat('Y-m-d',$date);
if($dateTime){
echo $date.' ok';
}
else {
echo 'wrong date '.$date;
}
I think you are expecting some thing like this.
<?php
$date1 = "2021-02";
$date2 = "2021-02-11";
$date3 = "2021-12";
$date4 = "2021-12-14";
$date1_array = explode("-", $date1);
$date2_array = explode("-", $date2);
$date3_array = explode("-", $date3);
$date4_array = explode("-", $date4);
if (count ($date1_array) == 3)
{
echo $date1 . ": It's a Date.";
echo "<br />";
}
if (count ($date2_array) == 3)
{
echo $date2 . ": It's a Date.";
echo "<br />";
}
if (count ($date3_array) == 3)
{
echo $date3 . ": It's a Date.";
echo "<br />";
}
if (count ($date4_array) == 3)
{
echo $date4 . ": It's a Date.";
echo "<br />";
}
?>

Error in comparison in php, to solve question with dates

i'm trying to do a contract management app using php and mysql and i'm having some questions regarding the dates.
I need to know the time that there is between today and specific dates in the contract, or if there is less than a month it should display days left..
the problem is that the comparison to know if the end of contract is in the past or in the future, does'n seems to work!
link to check the code: link to project
$hoje = date_create();
$fim = '2022-11-11';
$fim_data = date_create($fim);
$diff = date_diff( $hoje, $fim_data );
$meses = (($diff->format('%y')*12)+$diff->format('%m'));
$dias = $diff->days;
var_dump($fim < $hoje);
if($fim < $hoje) {
$result = "Contract has ended";
} elseif($meses >=1 ) {
$result = $meses . " months";
echo '<br>';
} else {
$result = $dias . " days";
};
echo '<br>';
echo $result;
You are comparing string with date object
Replace
if($fim < $hoje) {
With
if($fim_data < $hoje) {
Corrected code with solution by Felippe Duarte
$hoje = date_create();
$fim = '2018-11-11';
$fim_data = date_create($fim);
$diff = date_diff( $hoje, $fim_data );
$meses = (($diff->format('%y')*12)+$diff->format('%m'));
$dias = $diff->days;
var_dump($fim_data < $hoje);
if($fim_data < $hoje){$result = "não aplicavel";}
elseif($meses >=1 ){
$result = $meses . " meses";
echo '<br>';}
else{
$result = $dias . " dias";};
echo '<br>';
echo $result;

php check if date has passed

I'm getting dates from a Wordpress field and I need to check if the dates have past or still to come.
$dates = ['date'=>'02/12/13','date'=>'10/12/14','date'=>'14/01/15'];
foreach ($dates as $date){
$the_date = $date['date'];
echo $the_date;
echo " ";
echo date('d/m/y');
echo " ";
if($the_date < date('d/m/y')){
echo 'gone';
}else{
echo 'to come';
}
}
The foreach echos out this.
02/12/13 22/11/14 gone
10/12/14 22/11/14 gone
14/01/15 22/11/14 gone
27/01/15 22/11/14 to come
10/02/15 22/11/14 gone
It looks like it's just checking the first day date.
A better option is to use the DateTime class. It allows to compare two DateTime instances using comparison operators.
$dates = ['02/12/13','10/12/14','14/01/15'];
foreach ($dates as $date) {
$the_date = \DateTime::createFromFormat('d/m/y', $date);
$now = new \DateTime();
echo $date." ".($the_date < $now ? 'gone' : 'to come')."\n";
}
The problem you see is because the dates are being compared as strings. The current date is "22/11/14" so it will be greater than any other date with a day starting with "1" or "0".
PD: Your array contains many elements using the same 'date' key. That is a problem so I've removed them in my example.
<?php
$dates = array('02/12/13','10/12/14','14/01/15');
$now = mktime(0,0,0);
foreach($dates as $date) {
$tmp = explode('/',$date);
$date_time = mktime(0,0,0,intval($tmp[1]),intval($tmp[0]),intval($tmp[2]));
echo $date . ' ' . ($now > $date_time?'gone':'to come') . "\n";
}
Use PHP's DateTime API :
$date='02/12/13';
if(\DateTime::createFromFormat('d/m/y',$date) < new \DateTime()){
//date is in the past
}else{
//date is either today or in the future
}
Offical PHP doc:
http://php.net/manual/en/class.datetime.php
Best way is to use timestamp: Try this:
foreach ($dates as $date){
$the_date = $date['date'];
echo $the_date;
echo " ";
echo date('d/m/y');
echo " ";
if( strtotime($the_date) < time() )
{
echo ' is gone';
}
else
{
echo ' is to come';
}
}
Keep her simple:
// $date is the date you need to compare to today
$date = ("2015 10 03");
// Make sure their formats are purely numeric and match
if ($date->format('m.d.y') >= date('m.d.y'))
{
your procedure...
}
I suggest using the capabilities of the DateTime class instead. Then you can do the check as follows:
<?php
$then = $reset_date;
$then = new DateTime($then);
$now = new DateTime(date("m-d-Y"));
$sinceThen = $then->diff($now);
$new = new DateTime($reset_date);
$old = new DateTime(date("m-d-Y"));
if ( $old->modify('+1 year') < $new) {
echo "<font color='red'>Reset now <br></font>";
echo "<font color='orange'>$sinceThen->y years <br></font>";
echo "<font color='orange'>$sinceThen->m months </font>";
echo "<font color='orange'>$sinceThen->d days have passed.<br></font>";
} else {
echo "<font color='green'> $sinceThen->y years <br>
$sinceThen->m months $sinceThen->d days till to Reset.</font>";
//Combined
}
?>

Convert into Seconds from Double Data Type

I would like to ask of this kind of double data type can be converted into seconds?
In my database, the record is 6.80 means that 6 is hours and 80 is minutes. I want the output be 7 hours and 20 minutes. Is this possible?
Do the OOP way..!
For a 12-Hr Format.
<?php
$dt='6.80';
$date = DateTime::createFromFormat('H.i', $dt);
echo $date->format('g')." hours and ".$date->format('i')." minutes";
OUTPUT:
7 hours and 20 minutes
For a 24-Hr Format.
<?php
$dt='23.75';
$date = DateTime::createFromFormat('H.i', $dt);
$var= ($date->format('G')==0)?'00':$date->format('G');
echo $var." hours and ".$date->format('i')." minutes";
OUTPUT:
00 hours and 15 minutes
Example:
$t=6.80;
$s = $t - floor($t);
if($s>.60)
{
$t = $t -$s;
$t++;
$s=$s-.60;
$t=$t+$s;
}
floor() function is used to get the fractional part of a floating point number.
Try this
$str = "6.80";
$str = explode(".",$str);
$min = $str[0]*60 + $str[1];
$sec = $min*60;
echo date("H:i",$sec);
(Or)
$hour = intval($min/60);
$mins = $min%60;
echo "$hour:$mins";
this is another way:
<?php
$time = '9.102';
$tmp_min = strstr($time, '.');
$tmp_hour = strstr($time, '.', true);
$pos = strpos($time, '.');
$str_mins = substr($time, $pos+1);
$min = (int) ($str_mins);
if ( $min > 60 ) {
$ext_hour = floor($min/60);
$final_min = $min%60;
$final_hour = (int) ($tmp_hour + $ext_hour);
echo $final_hour . ' Hours and ' . $final_min . ' Minuts..';
}
else {
$final_hour = (int) ($tmp_hour);
$final_min = $min;
echo $final_hour . ' Hours and ' . $final_min . ' Minuts..';
}
?>

Categories