Unix timestamp to seconds, minutes, hours - php

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

Related

Get Time Difference (I already did a research but i just dont know how to fix it)

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

How to return the amount of years passed?

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

Calculates difference between two dates in PHP [duplicate]

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.

How can i display seconds ago/minutes ago/with unix timestamp?

I need the unix timestamp - the timestamp i have. Then display the time between like on twitter.
If you have the difference called diff:
$seconds = intval($diff) % 60;
$minutes = intval($diff/60) % 60;
$hours = intval($diff/3600) % 24;
$days = intval($diff/(3600*24));
Is this what you want ?
Not sure what language you need it, but if it will end up in a web page, you may try timeago.
Use example :
echo time_elapsed_string('#1367367755');
echo time_elapsed_string('#1367367755', true);
Output :
4 months ago
4 months, 2 weeks, 3 days, 1 hour, 49 minutes, 15 seconds ago
Link to the function.

Calculate the difference between date/times in PHP

I have a Date object ( from Pear) and want to subtract another Date object to get the time difference in seconds.
I have tried a few things but the first just gave me the difference in days, and the second would allow me to convert one fixed time to unix timestamp but not the Date object.
$now = new Date();
$tzone = new Date_TimeZone($timezone);
$now->convertTZ($tzone);
$start = strtotime($now);
$eob = strtotime("2009/07/02 17:00"); // Always today at 17:00
$timediff = $eob - $start;
** Note ** It will always be less than 24 hours difference.
Still gave somewhat wrong values but considering I have an old version of PEAR Date around, maybe it works for you or gives you an hint on how to fix :)
<pre>
<?php
require "Date.php";
$now = new Date();
$target = new Date("2009-07-02 15:00:00");
//Bring target to current timezone to compare. (From Hawaii to GMT)
$target->setTZByID("US/Hawaii");
$target->convertTZByID("America/Sao_Paulo");
$diff = new Date_Span($target,$now);
echo "Now (localtime): {$now->format("%Y-%m-%d %H:%M:%S")} \n\n";
echo "Target (localtime): {$target->format("%Y-%m-%d %H:%M:%S")} \n\n";
echo $diff->format("Diff: %g seconds => %C");
?>
</pre>
Are you sure that the conversion of Pear Date object -> string -> timestamp will work reliably? That is what is being done here:
$start = strtotime($now);
As an alternative you could get the timestamp like this according to the documentation
$start = $now->getTime();
To do it without pear, to find the seconds 'till 17:00 you can do:
$current_time = mktime ();
$target_time = strtotime (date ('Y-m-d'. ' 17:00:00'));
$timediff = $target_time - $current_time;
Not tested it, but it should do what you need.
I don't think you should be passing the entire Date object to strtotime. Use one of these instead;
$start = strtotime($now->getDate());
or
$start = $now->getTime();
Maybe some folks wanna have the time difference the facebook way. It tells you "one minute ago", or "2 days ago", etc... Here is my code:
function getTimeDifferenceToNowString($timeToCompare) {
// get current time
$currentTime = new Date();
$currentTimeInSeconds = strtotime($currentTime);
$timeToCompareInSeconds = strtotime($timeToCompare);
// get delta between $time and $currentTime
$delta = $currentTimeInSeconds - $timeToCompareInSeconds;
// if delta is more than 7 days print the date
if ($delta > 60 * 60 * 24 *7 ) {
return $timeToCompare;
}
// if delta is more than 24 hours print in days
else if ($delta > 60 * 60 *24) {
$days = $delta / (60*60 *24);
return $days . " days ago";
}
// if delta is more than 60 minutes, print in hours
else if ($delta > 60 * 60){
$hours = $delta / (60*60);
return $hours . " hours ago";
}
// if delta is more than 60 seconds print in minutes
else if ($delta > 60) {
$minutes = $delta / 60;
return $minutes . " minutes ago";
}
// actually for now: if it is less or equal to 60 seconds, just say it is a minute
return "one minute ago";
}

Categories