I am working with the PHP Carbon library. And I am trying to get the total time in minutes from a timestamp.
$time = new Carbon('02:13:23');
And I was wondering if there is a function like countMinutes() or totalMinutes() that would return in this case 133.38 which is 2 hours + 13 min + 23 sec. = 133.38
Or do I have to do it myself without the help of the library .. 120+13+(23/60)
Try the below code :
$time = Carbon::createFromTimeString('02:13:23');
$start_of_day = Carbon::createFromTimeString('02:13:23')->startOfDay();
$total_minutes = $time->diffInMinutes($start_of_day);
dd($time,$start_of_day,$total_minutes);
Here is a solution for getting minutes from a Carbon object.
// Create Carbon object from a specific date
$time = Carbon::createFromFormat('H:i:s', '02:13:23');
// Get days, hours and then minutes
$days = $startDate->diffInDays($time);
$hours = $startDate->copy()->addDays($days)->diffInHours($time);
$minutes = $startDate->copy()->addDays($days)->addHours($hours)->diffInMinutes($time);
echo $minutes;
Check the Carbon's documentation, there is a lot of good examples to get started.
Good luck!
Related
I have a form where I ask 4 hours, It's morning start and end hour and the same for afternoon.
I'm using Carbon but it returns me 0 if I put 30 minutes, it rounds to down.
I try with diffInHours and diffInMinutes but it rounds always down in both ways.
This is my code example:
$startTime1 = Carbon::createFromFormat('H:s', '09:00');
$startTime2 = Carbon::createFromFormat('H:s', '10:30');
$startTime3 = Carbon::createFromFormat('H:s', '14:00');
$startTime4 = Carbon::createFromFormat('H:s', '16:00');
$morningTime = $startTime2->diffInHours($startTime1);
$afternoonTime = $startTime4->diffInHours($startTime3);
$total = $morningTime + $afternoonTime;
In $morningTime it returns 1 and should return 1,30.
In $afternoonTime it returns 2 and it's correct.
If I use with diffInMinutes it put 60 in $morningTime and 120 in $afternoonTime. It's wrong again in morning time.
How can I solve that?
Thank you
You are assigning seconds H:s in the Carbon format, use H:i:
$startTime1 = Carbon::createFromFormat('H:i', '10:30');
And You can use format() method to format the difference in time
$morningTime = $startTime2->diff($startTime1)->format('%H:%I');
Edit: there is no way to combine dateInterval instance, but you still can use timestamp:
$total_in_seconds = ($startTime2->timestamp - $startTime1->timestamp) + ($startTime4->timestamp - $startTime3->timestamp);
$total = Carbon::createFromTimestamp($total_in_seconds)->format('h:i');
The timestamp in my database is 2015-03-03 00:25:39 (Take note that the type = timestamp and the correct current timestamp in my end is 2015-03-02 01:31:00. The difference should be around 23 hours. But now the problem is that the answers provided in the net will give me 30 hours instead of 23 hours. Some of the codes that I have tried are the following:
$target is the target date
CODE 1:
$then = strtotime($target);
$diff = $then - time();
echo sprintf("%s days and %s hours left", date('z', $diff), date('G', $diff));
But it gives me 1 days and 6 hours left. So 30 hours
CODE2:
$seconds = strtotime("$target") - time();
echo $seconds; exit();
$days = floor($seconds / 86400);
$seconds %= 86400;
$hours = floor($seconds / 3600);
echo $hours;
It gives me something like 107388 = 30 hours.
CODE 3:
//Convert to date
$datestr= $target;//Your date
$date=strtotime($datestr);//Converted to a PHP date (a second count)
//Calculate difference
$diff=$date-time();//time returns current time in seconds
$days=floor($diff/(60*60*24));//seconds/minute*minutes/hour*hours/day)
$hours=round(($diff-$days*60*60*24)/(60*60));
It gives me 6 hours
I don't know what I'm doing wrong, more like I have no idea how to do it.
This is now my last resort since I can't find the solution that will help me.
Hoping for your fast responses.
PHP's DateTime() (and DateInterval()) are much better for date math and returns the correct results:
$date = new DateTime('2015-03-03 00:25:39');
$now = new DateTime('2015-03-02 01:31:00');
$diff = $date->diff($now);
echo $diff->h, ' hours ', $diff->i, ' minutes';
Demo
This is a very late answer, but your question is a good one that will likely be searched for in the future.
Here is an online demo.
// this doesn't appreciate any timezone declarations, you'll need to add this if necessary
$target="2015-03-03 00:25:39"; // declare your input
$then=new DateTime($target); // feed input to DateTime
$now=new DateTime(); // get DateTime for Now
$diff=(array)$then->diff($now); // calculate difference & cast as array
$labels=array("y"=>"year","m"=>"month","d"=>"day","h"=>"hour","i"=>"minute","s"=>"second");
$readable=""; // declare as empty string
// filter the $diff array to only include the desired elements and loop
foreach(array_intersect_key($diff,$labels) as $k=>$v){
if($v>0){ // only add non-zero values to $readable
$readable.=($readable!=""?", ":"")."$v {$labels[$k]}".($v>1?"s":"");
// use comma-space as glue | show value | show unit | pluralize when necessary
}
}
echo "$readable";
// e.g. 2 years, 20 days, 1 hour, 10 minutes, 40 seconds
My friend and I are working on a fairly basic uptime script for an IRC Bot.
Here's our code:
function Uptime()
{
global $uptimeStart;
$currentTime = time();
$uptime = $currentTime - $uptimeStart;
$this->sendIRC("PRIVMSG {$this->ircChannel} :Uptime: ".date("z",$uptime)." Day(s) - ".date("H:i:s",$uptime));
}
$uptimeStart is set immediately when the script runs, as time();
for some reason when I execute this function, it starts at 364 days and 19 hours. I can't figure out why.
Your $uptime is not a timestamp as should be used in date(), but a difference in time. You have an amount of seconds there, not a timestamp (that corresponds with an actual date.
just use something like this to cacluate (quick one, put some extra brain in for things like 1 day, 2 hours etc) ;)
$minutes = $uptime / 60;
$hours = $minuts/60 ;
$days = $hours / 24
etc
If you have 5.3 or above, use the DateTime and DateInterval classes:
$uptimeStart = new DateTime(); //at the beginning of your script
function Uptime() {
global $uptimeStart;
$end = new DateTime();
$diff = $uptimeStart->diff($end);
return $diff->format("%a days %H:%i:%s");
}
You won't get anything meaninful by calling date() on that time difference. You should take that time difference and progressively divide with years, months, days, hours, all measured in seconds. That way you'll get what the time difference in those terms.
$daySeconds = 86400 ;
$monthSeconds = 86400 * 30 ;
$yearSeconds = 86400 * 365 ;
$years = $uptime / $yearSeconds ;
$yearsRemaining = $uptime % $yearSeconds ;
$months = $yearsRemaining / $monthSeconds ;
$monthsRemaining = $yearsRemaining % $monthSeconds ;
$days = $monthsRemaining / $daySeconds ;
.. etc to get hours and minutes.
date() function with second argument set to 0 will actually return you (zero-date + (your time zone)), where "zero-date" is "00:00:00 1970-01-01". Looks like your timezone is UTC-5, so you get (365 days 24 hours) - (5 hours) = (364 days 19 hours)
Also, date() function is not the best way to show the difference between two dates. See other answers - there are are already posted good ways to calculate difference between years
This question already has answers here:
Get interval seconds between two datetime in PHP?
(8 answers)
Closed last year.
HI, i have a couple of posts in my MySql database server, one of the info content in each post is the date and time in the format datetime (Ex. 2010-11-26 21:55:09) when the post was made.
So, i want to retrive the actual date and time from the SQL server with the function NOW() and calculates how many seconds or minutes or hours or days ago was post the info.
I dont know how to create this php script but i know that for sure is allready made, so thanks for any help.
you could use the date_diff() function
http://php.net/manual/en/function.date-diff.php
Something like...
<?php
$now = time();
$then = $posttime;
$diff = date_diff($now,$then);
echo $diff->format('%R%d days'); #change format for different timescales
?>
edit --
I actually solve this issue on one of my twitter apps using this function...
function time_since ( $start )
{
$end = time();
$diff = $end - $start;
$days = floor ( $diff/86400 ); //calculate the days
$diff = $diff - ($days*86400); // subtract the days
$hours = floor ( $diff/3600 ); // calculate the hours
$diff = $diff - ($hours*3600); // subtract the hours
$mins = floor ( $diff/60 ); // calculate the minutes
$diff = $diff - ($mins*60); // subtract the mins
$secs = $diff; // what's left is the seconds;
if ($secs!=0)
{
$secs .= " seconds";
if ($secs=="1 seconds") $secs = "1 second";
}
else $secs = '';
if ($mins!=0)
{
$mins .= " mins ";
if ($mins=="1 mins ") $mins = "1 min ";
$secs = '';
}
else $mins = '';
if ($hours!=0)
{
$hours .= " hours ";
if ($hours=="1 hours ") $hours = "1 hour ";
$secs = '';
}
else $hours = '';
if ($days!=0)
{
$days .= " days ";
if ($days=="1 days ") $days = "1 day ";
$mins = '';
$secs = '';
if ($days == "-1 days ") {
$days = $hours = $mins = '';
$secs = "less than 10 seconds";
}
}
else $days = '';
return "$days $hours $mins $secs ago";
}
You pass it in a unix timestamp of the time to check (the post time) and it returns the various string.
As billythekid said, you can use the date_diff() function if you are using PHP5.3+, if you are not then there are various methods. As shown by other posters. The quickest method in MySQL if you want to know the time split in to the "hours:mins:secs" hierarchy is to use the TIMEDIFF() function.
SELECT TIMEDIFF(NOW(), '2010-11-26 12:00:00');
If you want it as seconds, use the unix timestamp features in MySQL or in PHP, you can convert MySQL dates to PHP quickly using strtotime().
Usually, you do this kind of thing in a query, but MySQL isn't very good with intervals (it would be very easy with PostgreSQL). You could convert it to unix timestamp, then it would give the number of seconds between the two dates :
SELECT UNIX_TIMESTAMP() - UNIX_TIMESTAMP(your_datetime_column);
I thought about DATEDIFF, but it only returns the number of days between the two dates.
You can do it in PHP, for instance, with DateTime class :
$date1 = new DateTime();
$date2 = new Datetime('2010-11-26 12:00:00');
var_dump($date1->diff($date2));
(There's a procedural way to do this, if you're not a fan of OOP.)
This is definitely the solution I'd use if I can't do it with the RDBMS. DateTime::diff returns a DateInterval object, which contains the number of seconds, minutes, hours, days, etc. between the two dates.
You could also do it with timestamps in PHP :
$num_sec = time() - strtotime('2010-11-26 12:00:00');
Which would return the same thing as the SQL query.
An easy solution is possible from within the SQL Query:
SELECT UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(post_date) AS seconds_ago FROM posts
Documentation here: MySQL Ref
I actually needed to do this in PHP myself and while billythekid's post was in the right direction it fell short. I've minimized the code though it should be clear that the second parameter is from a database with a DATETIME column type.
<?php
$interval = date_diff(date_create(date('Y-m-d H:i:s')), date_create($row1['date']));
echo $interval->format('%R%a days');
//Database: 2019-02-22
//PHP's date: 2018-07-07
//Result: +306 days
?>
A reminder of the obvious: you can also just use substr($interval->format('%R%a days'),1) if you need just the integer.
I need to somehow take a unix timestamp and output it like below
Can this be done with MySQL? Or php
Mike 7s ago
Jim 44s ago
John 59s ago
Amanda 1m ago
Ryan 1m ago
Sarah 1m ago
Tom 2m ago
Pamela 2m ago
Ruben 3m ago
Pamela 5h ago
As you can guess i only wanna print the minute, not minutes and seconds(1m 3s ago)
What should I look into?
Yes it can be done. See related post
$before // this is a UNIX timestamp from some time in the past, maybe loaded from mysql
$now = time()
$diff = $now - $before;
if( 1 > $diff ){
exit('Target Event Already Passed (or is passing this very instant)');
} else {
$w = $diff / 86400 / 7;
$d = $diff / 86400 % 7;
$h = $diff / 3600 % 24;
$m = $diff / 60 % 60;
$s = $diff % 60;
return "{$w} weeks, {$d} days, {$h} hours, {$m} minutes and {$s} secs away!"
}
PHP 5.3 and newer have DateTime objects that you can construct with data coming back from a database. These DateTime objects have a diff method to get the difference between two dates as a DateInterval object, which you can then format.
Edit: corrected sub to diff.
Edit 2:
Two catches with doing it this way:
DateTime's constructor doesn't appear to take a UNIX timestamp... unless prefixed with an #, like this: $startDate = new DateTime('#' . $timestamp);
You won't know what the largest unit is without manually checking them. To get an individual field, you still need to use format, but with just a single code... Something like $years = $dateDiff->format('y');
function sECONDS_TO_DHMS($seconds)
{
$days = floor($seconds/86400);
$hrs = floor($seconds / 3600);
$mins = intval(($seconds / 60) % 60);
$sec = intval($seconds % 60);
if($days>0){
//echo $days;exit;
$hrs = str_pad($hrs,2,'0',STR_PAD_LEFT);
$hours = $hrs-($days*24);
$return_days = $days." Days ";
$hrs = str_pad($hours,2,'0',STR_PAD_LEFT);
}else{
$return_days="";
$hrs = str_pad($hrs,2,'0',STR_PAD_LEFT);
}
$mins = str_pad($mins,2,'0',STR_PAD_LEFT);
$sec = str_pad($sec,2,'0',STR_PAD_LEFT);
return $return_days.$hrs.":".$mins.":".$sec;
}
echo sECONDS_TO_DHMS(2); // Output 00:00:02
echo sECONDS_TO_DHMS(96000); // Output 1 Days 02:40:00
PHP's date() function
as well as time() and some others that are linked in those docs
This can also be done in Mysql with date and time functions
You can try my Timeago suggestion here.
It can give outputs like this:
You opened this page less than a
minute ago. (This will update every
minute. Wait for it.)
This page was last modified 11 days
ago.
Ryan was born 31 years ago.
I dont have a mysql server at hand, but a combination of the following commands should get you something like what you want.
DATEDIFF
AND
DATEFORMAT