Comparing datetimes in php not working - php

I have the following session value
$_SESSION["time"] = 2015-01-09 23:57:38 (example value)
And the variable $test
$test = time() - (60 * 1); (1 minute)
$test = date("Y-m-d H:i:s",$test);
What I want to do is check whether 1 minute as passed. To do this I have the following code:
if(isset($_SESSION["time"]) && (strtotime($_SESSION["time"]) > $test)){
echo "first";
}else{
echo "second";
}
Independently to which logic comparison I use (< or >), after a minute a page refresh still echoes the same... any idea on why? I'm finding this really strange...

Comparision should be like
($_SESSION["time"] > $test)
PHP now will compare two string values instead of integer (return value from strtotime call) and string (return value from date call)

What he actually wants is...
strtotime($_SESSION["time"]) > strtotime($test))

Related

A confusion about time() function in PHP

I cannot understand why the result of subtracting the current time from the variable of $_session['now'] that has included the previous time is zero.
I expected outputting the difference between the current time and the time when i have created the variable $student->now. Explain me please.
class Student
{
public function __set($key, $value)
{
$_SESSION[$key] = $value ;
}
public function __get($key)
{
return $_SESSION[$key];
}
}
session_start();
$student = new Student() ;
//__set function will be called ;
$student->now = time();
//__get function will be called ;
echo time() - $_SESSION["now"]; // output is zero ?!
The $_session['now'] variable is set in the line before the echo.
In the echo line the current time is compared to the time set in the line before.
Because both lines are executed directly after each other, both are executed within the same second. There will be a difference of milliseconds but time() function is measured in seconds, refer to: https://www.php.net/manual/en/function.time.php.
That's why both timestamps are the same and there is no difference between these when comparing them.
time() has a precision of ONE second, you are basically doing:
$now = time(); // e.g. 1627385278
echo time() - $now; // 1627385278 - 1627385278
This happens very fast, so the output is (almost always) zero.
The fact that your example code involves a "session" hints that you want to measure time between different HTTP requests. If that is the case, some logic is needed to ONLY set the stored value for the first time, but not thereafter.

PHP Convert Minutes+Seconds to Seconds

Currently, I have the following time format like the following:
0m12.345s
2m34.567s
I put them in variable $time. How do I convert the variable to seconds only in PHP, like 12.345 for the first one, and 154.567 for the second one?
You can do it like this,
//Exploding time string on 'm' this way we have an array
//with minutes at the 0 index and seconds at the 1 index
//substr function is used to remove the last s from your initial time string
$time_array=explode('m', substr($time, 0, -1));
//Calculating
$time=($time_array[0]*60)+$time_array[1];
<?php
$time="2m34.567s";
$split=explode('m',$time);
// print_r($split[0]);
$split2=explode('s',$split[1]);
$sec= seconds_from_time($split[0])+$split2[0];
echo $sec;
function seconds_from_time($time) {
return $time*60;
}
?>
Demo here http://phpfiddle.org/main/code/gdf-3tj

compare times with hundredths in php

I try to compare two swim times in php. They are like HH:MM:SS.XX (XX are hundreths). I get them as string and i want to find out which swimmer is faster. I tryed to convert them using strtotime(). It works with hours, minutes and seconds but it ignores hundreths. Here is my code for better explanation:
$novy = strtotime($input1);
$stary = strtotime($input2);
if($novy < $stary){
//change old(stary) to new(novy)
}
If $input1 is 00:02:14.31 and $input2 is 00:02:14.32 both $novy and $stary are 1392850934.
I read some solution to similar problem in javascript but I can`t use it, this must be server-side.
Thank you for help.
If you use date_create_from_format you can specify the exact date format for php to convert the string representations to:
<?php
$input1 = '00:02:14.31';
$input2 = '00:02:14.32';
$novy = date_create_from_format('H:i:s.u', $input1);
$stary = date_create_from_format('H:i:s.u',$input2);
if ($novy < $stary) {
echo "1 shorter\n";
} else {
echo "2 longer\n";
}
Recommended reading: http://ie2.php.net/datetime.createfromformat
If the format is really HH:MM:SS.XX (ie: with leading 0's), you can just sort them alphabetically:
<?php
$input1 = '00:02:14.31';
$input2 = '00:02:14.32';
if ($input1 < $input2) {
echo "1 faster\n";
} else {
echo "2 faster\n";
}
It prints 1 faster
You could write some conditional logic to test if HH::MM::SS are identical, then simply compare XX, else use the strtotime() function that you are already using
You are working with durations, not dates. PHP's date and time functions aren't really of any help here. You should parse the string yourself to get a fully numeric duration:
$time = '00:02:14.31';
sscanf($time, '%d:%d:%d.%d', $hours, $minutes, $seconds, $centiseconds);
$total = $centiseconds
+ $seconds * 100
+ $minutes * 60 * 100
+ $hours * 60 * 60 * 100;
var_dump($total);
The total is in centiseconds (100th of a second, the scale of your original input). Multiply/divide by other factors to get in others scales, as needed.

Check whether day is specified in a date string

Test case scenario - User clicks on one of two links: 2012/10, or 2012/10/15.
I need to know whether the DAY is specified within the link. I am already stripping the rest of the link (except above) out of my URL, am I am passing the value to an AJAX request to change days on an archive page.
I can do this in either JS or PHP - is checking against the regex /\d{4}\/\d{2}\/\d{2}/ the only approach to seeing if the day was specified or not?
You can also do this if you always get this format: 2012/10 or 2012/10/15
if( str.split("/").length == 3 ) { }
But than there is no guaranty it will be numbers. If you want to be sure they are numbers you do need that kind of regex to match the String.
You could explode the date by the "/" delimiter, then count the items:
$str = "2012/10";
$str2 = "2012/10/5";
echo count(explode("/", $str)); // 2
echo count(explode("/", $str2)); // 3
Or, turn it into a function:
<?php
function getDateParts($date) {
$date = explode("/", $date);
$y = !empty($date[0]) ? $date[0] : date("Y");
$m = !empty($date[1]) ? $date[1] : date("m");
$d = !empty($date[2]) ? $date[2] : date("d");
return array($y, $m, $d);
}
?>
I would personally use a regex, it is a great way of testing this sort of thing. Alternatively, you can split/implode the string on /, you will have an array of 3 strings (hopefully) which you can then test. I'd probably use that technique if I was going to do work with it later.
The easiest and fastest way is to check the length of the string!
In fact, you need to distinguish between: yyyy/mm/dd (which is 10 characters long) and yyyy/mm (which is 7 characters).
if(strlen($str) > 7) {
// Contains day
}
else {
// Does not contain day
}
This will work EVEN if you do not use leading zeros!
In fact:
2013/7/6 -> 8 characters (> 7 -> success)
2013/7 -> 6 characters (< 7 -> success)
This is certainly the fastest code too, as it does not require PHP to iterate over the whole string (as using explode() does).

Subtraction with php and mysql

I am developing a joomla extension and in default.php file i have this code:
foreach($this->subv as $subv) {
$giorni = ((int)$subv->data_fine - (int)$subv->data_inizio);
$ore = ($giorni * 24) % 24;
echo $giorni.' : '.$ore;
}
$this->subv is an object that contains the result of a mysql query. My problem is that echo prints $subv->data_fine value, and not the result of the substraction. $subv->data_fine and $subv->data_inizio contain the result of time() function.
How can i resolve it this problem?
Thanks!
If I understand you problem correctly, $giorni is equal to $subv->data_fine, which would simply mean that (int)$subv->data_inizio evaluates to zero. Have you checked that?
You can use mysql to get the difference between 2 dates (DATEDIFF function):
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_datediff

Categories