Convert datetime into time ago [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I need to convert DateTime into the year, month, days, hours, minutes, seconds ago like as yahoo question asked 5week ago, or 1 year ago or 1 month ago, my date is saved in the database like this: 2011-11-30 05:25:50.
Now I want to show like year, month, days, hours, minutes and seconds in PHP like: how much year, how many months , days, hours, minutes, seconds ago, but need only one time unit show like it will be year or days or hours or minutes or seconds.
I have searched about this but not understand how I can do this, I know there are many questions at this topic on Stack Overflow, maybe it is duplicate but I am unable to solve my issue.
Thanks in advance.

Assuming you mean relative to the present (if you don't, please clarify your question), you could use this:
$then = new DateTime('2011-11-30 05:25:50');
$now = new DateTime();
$delta = $now->diff($then);
$quantities = array(
'year' => $delta->y,
'month' => $delta->m,
'day' => $delta->d,
'hour' => $delta->h,
'minute' => $delta->i,
'second' => $delta->s);
$str = '';
foreach($quantities as $unit => $value) {
if($value == 0) continue;
$str .= $value . ' ' . $unit;
if($value != 1) {
$str .= 's';
}
$str .= ', ';
}
$str = $str == '' ? 'a moment ' : substr($str, 0, -2);
echo $str;
Output:
1 year, 9 months, 17 days, 14 hours, 31 minutes, 31 seconds

I've always used this function:
function when($datetime) {
define("SECOND", 1);
define("MINUTE", 60 * SECOND);
define("HOUR", 60 * MINUTE); define("DAY", 24 * HOUR);
define("MONTH", 30 * DAY); $delta = time() - strtotime($datetime);
// convert
if($delta < 1 * MINUTE) { return $delta == 1 ? "one second ago" : $delta." seconds ago"; }
if($delta < 2 * MINUTE) { return "a minute ago"; } if($delta < 45 * MINUTE) { return floor($delta / MINUTE)." minutes ago"; }
if($delta < 90 * MINUTE) { return "an hour ago"; } if($delta < 24 * HOUR) { return floor($delta / HOUR)." hours ago"; }
if($delta < 48 * HOUR) { return "yesterday"; } if($delta < 30 * DAY) { return floor($delta / DAY)." days ago"; }
if($delta < 12 * MONTH) { $months = floor($delta / DAY / 30); return $months <= 1 ? "one month ago" : $months." months ago"; }
else { $years = floor($delta / DAY / 365); return $years <= 1 ? "one year ago" : $years." years ago"; }
}
echo when(YOUR DATE HERE) will return the best format of relative time, which might be days, hours, or if it wasn't that long ago, even in seconds.

Try this:
http://www.php.net/manual/en/function.strtotime.php
PHP has a nice function strtotime all ready for your needs.
That'll give you a timestamp, then you can just do math from there from whatever date you are subtracting from.

You could try splitting this using preg_split.
Try something like
$output = preg_split( "/ (-| |:) /", $input );
That should give you an array, where the first element is the year, second is the month, and so on.

Related

How do i convert the following hours in to minutes? [duplicate]

This question already has answers here:
Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...
(32 answers)
How to convert hh:mm:ss to minutes
(7 answers)
Closed 4 years ago.
$time_frame = floor(abs((strtotime($notification['note_date'])-strtotime(date("Y-m-d H:i:s")))/60/60));
if($time_frame>24){
$time_frame = floor($time_frame/24);
if($time_frame>1){
$time_frame = $time_frame." days ago";
} else{
$time_frame = $time_frame." day ago";
}
} else if($time_frame>1) {
$time_frame = $time_frame." hours ago";
} else if($time_frame==1) {
$time_frame = $time_frame." hour ago";
} else{
$time_frame = "1 hour ago"; //I want to break this hour in to minutes
}
How do i break that hour in to display in to minutes, last else statement.
I recommend dealing with seconds/timestamps or date-time objects instead - this would be a better and more dynamic approach in my opinion. Perhaps have a look at this question instead Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...
That said, if you want to do it with your current approach, you can multiply your variable by 60 (as there is 60 minutes in an hour), such as
$time_frame = 60*$timeframe;
Examples,
If $timeframe is 1, then you have exactly one hour. 60min * 1 = 60 minutes.
If $timeframe is 0.5, that would be half an hour. 60min * 0.5 = 30 minutes.
If $timeframe is 0.25, means that 15 minutes have passed, and 60min * 0.25 = 15 minutes.
You might want to round that number to your liking, so that you will not get output such as 1.43 minutes left. Also note that floating point numbers may not be exactly accurate, hence my recommendation of using datetime objects or timestamps instead.
If you use the DateTime class, you can use the diff() method so you don't have to mess with all the calculating. diff() returns a DateInterval which has public properties you can use to determine the appropriate message.
$interval = date_create($notification['note_date'])->diff(new DateTime);
if ($interval->days > 1) {
$time_frame = "{$interval->days} days";
} elseif ($interval->days == 1) {
$time_frame = "1 day";
} elseif ($interval->h > 1) {
$time_frame = "{$interval->h} hours";
} elseif ($interval->h == 1) {
$time_frame = "1 hour";
} elseif ($interval->i > 1) {
$time_frame = "{$interval->i} minutes";
} elseif ($interval->i == 1) {
$time_frame = "1 minute";
} else {
$time_frame = "Less than 1 minute";
}
echo "{$time_frame} ago";
You can actually USE that string! :-D
$x = new DateTime('1 hour ago'); // done at 17:17
echo $x->format('Y-m-d H:i:s'); // outputs 2018-10-23 16:17:12
https://3v4l.org/jWTC8

Comparing MYSQL timestamps to retrieve time passed in specific units

Here is a PHP function I have designed, which is supposed to determine the amount of time passed in secs,mins,hours,days,weeks,months, and years - depending upon which bracket it is beneath. However Ive noticed that the values being returned seem to increase faster than actual time (within 30 mins, it outputs "1 weeks ago"). Im wondering if $time is actually in millis? That said, for the first 2 mins it outputs relatively accurate results.
Note: Running on 1and1 host.
Here's the function:
function get_relative_date($conn,$date,$post_id){
#get current timestamp
$q = "SELECT NOW() - INTERVAL 1 HOUR - `timestamp` FROM `posts` WHERE id=".$post_id.";";
# - INTERVAL 1 HOUR added due to server running 1 hour ahead.
$result = mysqli_query($conn,$q);
if ($result != null && $result != false){
$row = mysqli_fetch_array($result,MYSQLI_BOTH);
$time = $row[0]; #time passed since post
$min = 60;
$hour = $min*60;
$day = $hour*24;
$week = $day*7;
$month = $week*4;
$year = $month*12;
if ($time < $min){
return $time." secs ago";
}
if ($time < $hour){
return round(($time / $min))." mins ago";
}
if ($time < $day){
return round(($time / $hour))." hours ago";
}
if ($time < $week){
return round(($time / $day))." days ago";
}
if ($time < $month){
return round(($time / $week))." weeks ago";
}
if ($time < $year){
return round(($time / $month))." months ago";
}
if ($time >= $year){
return round(($time / $year))." years ago.";
}
return false;
}
}
Cheers.
I tried your query out and instead of 2 minutes and 40 seconds (in seconds) I was receiving 240 and instead of 1 hour 3 minutes and 40 seconds (in seconds) I got 10340.
You need this:
SELECT TIME_TO_SEC(TIMEDIFF(NOW(),`timestamp`)) FROM `posts` ...
This will select the time difference in seconds and hopefully give you the desired result.

Need to rewrite function for date display

I have the following function that I wrote couple of years ago. It takes a datetime from my db and displays it in a better formatted way.
function formatTime($dateTime){
// show time only if posted today
if (date('Ymd') == date('Ymd', strtotime($dateTime))) {
$dt = date('g:i a', strtotime($dateTime));
} else {
// if not the same year show YEAR
if (date('Y') == date('Y', strtotime($dateTime))) {
$dt = date('M j', strtotime($dateTime));
} else {
$dt = date('M j, Y', strtotime($dateTime));
}
}
return $dt;
}
I use server time, which is CST for me. Yesterday I had a user from Australia pointing out that for him it did not make any since since he way on an entirely different time zone, actually a day ahead (when compared to my output at certain time :).
I decided to rewrite my function to say something like:
if under a minute > seconds ago
if under an hour > # minutes ago
between 1 -2 hrs > over an hour ago
2 - 24 hrs > day ago
2 - 7 days > # days ago
7 days - month > # weeks ago
1 - 2 months > over a month
after that I can just show a date
Are there any functions that you are perhaps aware of doing this, if not how would I modify this one?
Thanks.
function formatTime ($dateTime) {
// A Unix timestamp will definitely be required
$dateTimeInt = strtotime($dateTime);
// First we need to get the number of seconds ago this was
$secondsAgo = time() - $dateTimeInt;
// Now we decide what to do with it
switch (TRUE) {
case $secondsAgo < 60: // Less than a minute
return "$secondsAgo seconds ago";
case $secondsAgo < 3600: // Less than an hour
return floor($secondsAgo / 60)." minutes ago";
case $secondsAgo < 7200: // Less than 2 hours
return "over an hour ago";
case $secondsAgo < 86400: // Less than 1 day
return "1 day ago"; // This makes no sense, but it is what you have asked for...
case $secondsAgo < (86400 * 7): // Less than 1 week
return floor($secondsAgo / 86400)." days ago";
case $secondsAgo < (86400 * 28): // Less than 1 month - for the sake of argument let's call a month 28 days
return floor($secondsAgo / (86400 * 7))." weeks ago";
case $secondsAgo < (86400 * 56): // Less than 2 months
return "over a month ago";
default:
return date('M j, Y', $dateTimeInt);
}
}
This is by no means flawless, especially since one of your requirements doesn't make sense (see comments) but hopefully it should give you a push in the right direction, and illustrate how you can use switch to allow you to easily add and remove items/options from the behaviour.

Is there a library or known function for StackOverflow's/Reddit's date system? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
For example, when you submit a post it might say "submitted 1 second ago." and if it was 2 weeks old it would say that. Did SO and Reddit write these or is there a PHP/SQL function that converts the date in to a more human readable and relevant format such as this?
I'd highly suggest checking out John Resig's pretty date library:
http://ejohn.org/blog/javascript-pretty-date/
As shown on that blog post, you can do things like this:
prettyDate("2008-01-28T20:24:17Z") // => "2 hours ago"
prettyDate("2008-01-27T22:24:17Z") // => "Yesterday"
prettyDate("2008-01-26T22:24:17Z") // => "2 days ago"
prettyDate("2008-01-14T22:24:17Z") // => "2 weeks ago"
prettyDate("2007-12-15T22:24:17Z") // => undefined
They are called fuzzy dates/times and there are many libraries for JavaScript and PHP.
there's lots of ways todo it but if you want to use php then this function will output it in a nice way just put a unix timestamp in
function timeDiffrence($from, $to = null){
$to = (($to === null) ? (time()) : ($to));
$to = ((is_int($to)) ? ($to) : (strtotime($to)));
$from = ((is_int($from)) ? ($from) : (strtotime($from)));
$units = array
(
" Years" => 29030400, // seconds in a year (12 months)
" Months" => 2419200, // seconds in a month (4 weeks)
" Weeks" => 604800, // seconds in a week (7 days)
" Days" => 86400, // seconds in a day (24 hours)
" Hours" => 3600, // seconds in an hour (60 minutes)
" Minute" => 60, // seconds in a minute (60 seconds)
" Second" => 1 // 1 second
);
$diff = abs($from - $to);
$suffix = (($from > $to) ? (" from now") : (" "));
foreach($units as $unit => $mult)
if($diff >= $mult)
{
$and = (($mult != 1) ? ("") : ("and "));
$output .= "".$and.intval($diff / $mult)."".$unit.((intval($diff / $mult) == 1) ? (", ") : ("'s, "));
$diff -= intval($diff / $mult) * $mult;
}
$output .= " ".$suffix;
$output = substr($output, strlen(""));
if($output =='go' || $output ==' ago'){$output = 'A few secs ago';}
return 'Posted '.str_ireplace('1 Days','1 Day',trim($output,', ')).' ago';
}

Pretty printing library for time differences in PHP [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 9 years ago.
Improve this question
Is there any good pretty printing library for UNIX timestamp differences . Something on the likes of the things seen in social networking sites like "x minutes ago" , "x hours ago" , "x days ago" etc . I know that it won't be hard to write on my own but why reinvent the wheel?
try
<?php
function rel_time($from, $to = null)
{
$to = (($to === null) ? (time()) : ($to));
$to = ((is_int($to)) ? ($to) : (strtotime($to)));
$from = ((is_int($from)) ? ($from) : (strtotime($from)));
$units = array
(
"year" => 29030400, // seconds in a year (12 months)
"month" => 2419200, // seconds in a month (4 weeks)
"week" => 604800, // seconds in a week (7 days)
"day" => 86400, // seconds in a day (24 hours)
"hour" => 3600, // seconds in an hour (60 minutes)
"minute" => 60, // seconds in a minute (60 seconds)
"second" => 1 // 1 second
);
$diff = abs($from - $to);
$suffix = (($from > $to) ? ("from now") : ("ago"));
foreach($units as $unit => $mult)
if($diff >= $mult)
{
$and = (($mult != 1) ? ("") : ("and "));
$output .= ", ".$and.intval($diff / $mult)." ".$unit.((intval($diff / $mult) == 1) ? ("") : ("s"));
$diff -= intval($diff / $mult) * $mult;
}
$output .= " ".$suffix;
$output = substr($output, strlen(", "));
return $output;
}
?>
I don't know if there's a library for PHP for this, but Jeff (who created this website) asked this question a long time ago. See this question for details. I'm sure you could get a lot of inspiration from that. Jeff even answers that question with the code they use on StackOverflow itself.
I don't think it would be that hard to write this yourself, so why not spend 5 minutes writing it instead of half an hour looking for a library?
PHP has a class built-in for this from PHP 5.3 onwards:
DateInterval
Use the format() method to get the output you wish for, though you need to decide on the necessary units I think.
defined('SECOND') ? NULL : define('SECOND', 1);
defined('MINUTE') ? NULL : define('MINUTE', 60 * SECOND);
defined('HOUR') ? NULL : define('HOUR', 60 * MINUTE);
defined('DAY') ? NULL : define('DAY', 24 * HOUR);
defined('MONTH') ? NULL : define('MONTH', 30 * DAY);
defined('YEAR') ? NULL : define('YEAR', 12 * MONTH);
class Time{
public $td;
public function set_td($timestamp){
$this->td = time() - $timestamp;
}
public function string_time($timestamp){
$this->set_td($timestamp);
if ($this->td < 0){
return "not yet";
}
if ($this->td < 1 * MINUTE){
return $this->td <= 1 ? "just now" : $this->td." seconds ago";
}
if ($this->td < 2 * MINUTE){
return "a minute ago";
}
if ($this->td < 45 * MINUTE){
return floor($this->td / MINUTE)." minutes ago";
}
if ($this->td < 90 * MINUTE){
return "an hour ago";
}
if ($this->td < 24 * HOUR){
return floor($this->td / HOUR)." hours ago";
}
if ($this->td < 48 * HOUR){
return "yesterday";
}
if ($this->td < 30 * DAY){
return floor($this->td / DAY)." days ago";
}
if ($this->td < 12 * MONTH){
$months = floor($this->td / MONTH);
return $months <= 1 ? "one month ago" : $months." months ago";
}else{
$years = floor($this->td / YEAR);
return $years <= 1 ? "one year ago" : $years." years ago";
}
}
}
$time = new Time();
Simply put your timestamp into the new object and recievi the time diffenrece in seconds.e.g.
$string = $time->string_time($timestamp);

Categories