PHP - Converting Seconds to Minutes discrepancy - php

I'm running into a discrepancy with either my conversion of an integer into defined Minutes.
<?php
$seconds = 269;
echo date("G:i:s", $seconds);
// result: 0:04:29
?>
I figured I'd double check on some sites to see if the conversion is correct:
Here's one I found:
http://www.thecalculatorsite.com/conversions/time.php
The result returned is: 4.4833333333333
Example 1 returns: 0:04:29
Example 2 returns: 4.4833333333333
I'm confused about this.
What am I missing here. Am I using the date() function incorrectly?

Be careful with date(). it expects to be provided with a PHP timestamp, which is number of seconds since midnight, Jan 1/1970. It will "work" for small timestamp values, but will get increasingly wrong as you pass in "larger" timestamps, as you will be dealing with months/days/years in 1970, plus leapyears, etc...
As for the conversion, what's wrong with it? 4.48333... is 4 full minutes, and 0.483333 is simply 29/60.

You can use DateTime class for time calculation:
Code:
$start = new DateTime;
$end = clone $start;
$end->modify('+269 seconds');
$diff = $start->diff($end);
print_r($diff);
Output:
DateInterval Object
(
[y] => 0
[m] => 0
[d] => 0
[h] => 0
[i] => 4
[s] => 29
[invert] => 0
[days] => 0
)
As you can see in output, you have all the info you need. To access it, just use $diff->i for minutes, $diff->s for seconds etc.

Related

String timestamp to int, make a DateTime with it afterwards in PHP

I want to know if a timestamp stored in my database as a bigint (I'm using mariaDB) is already old comparing it to the current date, there's one example:
I have this timestamp stored in my db = 1560499685530 but for some reason, it is a string when I fetch it from my db so I got this error when trying to set its timestamp (setTimestamp($timestamp))
DateTime::setTimestamp() expects parameter 1 to be integer, string
given
I tried using intval but my timestamp seems to be too long to be int because when I use inval it returns another int, smaller than mine, I guess that's the PHP int cap
I want my PHP to print if it's already an old date comparing it to the current date and wrote this code
$qBloqueo = mysqli_query($conn, "SELECT * FROM dates WHERE idUsuario = '$idUsuario'") or die(mysqli_error($conn));
$timestamp = mysqli_fetch_assoc($qBloqueo);
$timestamp = intval($timestamp['timestamp']); // Getting the timestamp from my db which is a string, still dunno why, in my db it's a bigint
$today = new DateTime();
$expireDate = new DateTime();
$expireDate->setTimestamp($timestamp);
if($today->format("Y-m-d") > $expireDate->format("Y-m-d")) {
print('Old date ^u^');
} else {
print('Not yet');
}
How can I use a timestamp to make a date obj without been a int or there is any way to convert it from a string to int? I just want to make a date from a string timestamp so I could compare it to the current date
If only type is concern then you can type cast variable like:
$timestamp = (int) $timestamp['timestamp'];
If you're looking for difference between two times
<?php
$time1 = new DateTime('09:00:59');
$time2 = new DateTime('09:01:00');
$interval = $time1->diff($time2);
echo $interval->format('%s second(s)');
?>
Output :
1 second(s)
Now to find difference between two timestamps
/* PHP/5.5.8 and later */
$start = new DateTimeImmutable('2016-04-20 00:37:15');
$end = $start->modify('+7 days');
$diff = $end->diff($start);
print_r($diff);
Output :
DateInterval Object ( [y] => 0 [m] => 0 [d] => 7 [h] => 0 [i] => 0 [s] => 0 [f] => 0 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 1 [days] => 7 [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 )
To convert date timestamp into millisecond
$yourdate = '2016-03-22 14:30';
$stamp = strtotime($yourdate); // get unix timestamp
$time_in_ms = $stamp*1000;
print_r($time_in_ms);
Output :
1458657000000
You can convert both times into millisecond and find which one is greater.
I hope this helps in some way

Problem in understanding datetime difference and invert

I am having a problem in understanding the difference between datetime. I am using PHP datetime class.
Here is a small part of my code to calculate the datetime difference:
date_default_timezone_set("Asia/Kolkata");
function timeline_date($date)
{
$today = new DateTime();
$timeline_date = new DateTime($date);
$interval = $today->diff($timeline_date);
echo "<pre>";
print_r($today);
print_r($timeline_date);
print_r($interval);
echo "</pre>";
}
$date = "2019-02-02 04:36:02";
echo timeline_date($date);
What is the meaning of statement:
$interval = $today->diff($timeline_date);
Is it subtracting $timeline_date from $today?
Or is it subtracting $today from $timeline_date?
I am having a great confusion regarding this particular statement. I searched on Internet but nothing is clearly mentioned on it.
Also $timeline_date can be past or future date and even today's date. So does it matter we should subtract small quantity from large quantity?
I get following output from above code:
DateTime Object
(
[date] => 2019-02-05 16:11:37
[timezone_type] => 3
[timezone] => Asia/Kolkata
)
DateTime Object
(
[date] => 2019-02-02 04:36:02
[timezone_type] => 3
[timezone] => Asia/Kolkata
)
DateInterval Object
(
[y] => 0
[m] => 0
[d] => 3
[h] => 11
[i] => 35
[s] => 35
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 1
[days] => 3
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)
We can see [invert] => 1 in above array. What is actual meaning of it? If I change the $date to:
$date = "2019-02-10 04:36:02";
Then [invert] => 0 changes to 1. Why? Does it mean if we have past date in difference then invert will be 0 and if we have future date then this array element will be 1?
DateTime::diff gives you the difference between the two dates, somewhat obviously. It doesn't really matter which one is bigger or smaller, a delta is a delta regardless of that. However, the resulting DateInterval object does note which one was bigger or smaller with the DateInterval::$invert property:
Is 1 if the interval represents a negative time period and 0 otherwise. See DateInterval::format().
The rule is if $b in $a->diff($b) is before $a, $invert is 1. Looking at said DateInterval::format, you'll see:
R Sign "-" when negative, "+" when positive
r Sign "-" when negative, empty when positive
So, if you do care about the future/past difference, you can use the %R/%r formatting parameters in DateInterval::format to output a "-" and/or "+". If you don't care, just omit that option and it's irrelevant.

How to calculate time difference between SQL time and PHP time

I have set times in SQL in this format: 2016-01-03 12:13:26.
I would like to calculate the number of hours and minutes (if hours<1) going from NOW() to that particular SQL time.
I've been looking at all the different threads here but I can't seem to grasp how to convert PHP different time formats to SQL's.
This is the code I've been using, but this will only give me back hours up to 12, and minutes also. Don't know how to use it with days.
$now = date("d/m/Y h:i:s");
$commentime = strtotime($SQLTIME);
$timetocomment = $now - $commentime;
For instance, this code will yield "12 hours ago" for data I posted 24 hours ago to SQL.
How can I do it? Thank you.
This is my suggestion to use date() in this format date("Y-m-d h:i:s"). Than you will get the complete difference in an array.
function dateDifference($date_1 ,$date_2)
{
$datetime1 = date_create($date_1);
$datetime2 = date_create($date_2);
$interval = date_diff($datetime1, $datetime2);
return $interval;
}
$now = date("Y-m-d h:i:s");
$sqlTime = "2016-01-03 12:13:26";
$DateDiffArr = dateDifference($now,$sqlTime);
echo "<pre>";
print_r($DateDiffArr);
Result Is:
DateInterval Object
(
[y] => 0
[m] => 0
[d] => 0
[h] => 22
[i] => 45
[s] => 55
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 1
[days] => 0
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)
In resultant array, you can get the all difference as you need like in years, months, days, minutes, seconds etc.

php datetime difference returning incorrect result

so i have this code in php :
$now= new \Datetime("UTC");
$lv=$user->getLastVisit();
$interval =$lv->diff($now,true);
print_r($interval);
print_r("<br>".$lv->format("Y-m-d H:i:s"));
print_r("<br>".$now->format("Y-m-d H:i:s"));
exit(0);
and this is the output :
DateInterval Object ( [y] => 0 [m] => 0 [d] => 0 [h] => 6 [i] => 59 [s] => 6 [invert] => 0 [days] => 0 )
2013-04-09 23:44:21
2013-04-09 23:45:15
so the difference result is 6 hours 59 minutes and 6 seconds ! but if i do the difference manually i have 54 seconds !! so what's wrong with this DateTime::diff function ?
Edit:
this is the var_dump($user->getLastVisit());
2013-04-09 23:54:59object(DateTime)#320 (3) { ["date"]=> string(19) "2013-04-09 23:44:21" ["timezone_type"]=> int(3) ["timezone"]=> string(19) "America/Los_Angeles" }
The last login time should be 23:44 UTC, not Los_Angeles. (As of this writing, it still isn't 2013-04-09 23:44:21 in Los Angeles!)
It seems that you might be storing the last login time in your database as UTC, but when pulling back out of your database PHP is using the local/default timezone, and treating it as America/Los_Angeles.
See here: http://3v4l.org/elbLY
Notice that I'm setting $now to the exact same time (in UTC) that you had, and I'm using your $lv time as well, first in Los_Angeles timezone and then in UTC.
The first interval is what you got, the second interval is showing the 54 seconds correctly.
So you need to fix your $user->getLastVisit() method and ensure that it hands you that date in the UTC, and your diff will work.

Countdown to sunday

I am currently looking at creating a script for my site that will count down to sunday of that week, every week.
Example:
The user visits the site on a saturday at 11:30am, they will be greeted with:
"The next time this page will be updated is in 0 days, 12 hours and 30 minutes."
Any ideas?
You can use this little trick to get a timestamp for midnight next Sunday:
$sunday = strtotime('next Sunday');
See this answer for how to format it into something useful. Right now I get this:
print_r(dateDifference($sunday, time()));
Array
(
[years] => 0
[months_total] => 0
[months] => 0
[days_total] => 0
[days] => 0
[hours_total] => 4
[hours] => 4
[minutes_total] => 256
[minutes] => 16
[seconds_total] => 15387
[seconds] => 27
)
I am using similar to this solution in one of my pojects. You can use it like this:
ago(strtotime("next sunday")) but you need to change $difference = $now - $time; to $difference = $time - $now;
Here's one solution:
http://jsfiddle.net/foxbunny/xBE7L/
It also automatically updates every second.
Edit: I've included the offset parameter, and you use it to supply the difference between user's and server's time-zone if necessary.

Categories