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

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

Related

Why is my relative time function saying that 0 in unix time stamp is 49 years ago?

I spent some time doing this quick little function (I didn't use the default one because I wanted a bit more customization later on). I made a post that has $checkTime = '0';, and when run through this function it comes back as 49 years ago.
Why is it returning that when January 1970 was only 45 years ago? Are the extra 4 years coming from time differences and leap years?
The other times seem to work correct (recent ones), but the ones I set to 0 say that and I'm just curious where the bug is, or what I might be overlooking.
function relativeTime($string) {
$currentTime = time();
$checkTime = $string;
$timeDifference = $currentTime - $checkTime;
if($timeDifference > '0') {
$timeSeconds = round(($timeDifference / 60) * 60);
$timeMinutes = round($timeSeconds / 60);
$timeHours = round($timeMinutes / 60);
$timeDays = round($timeHours / 24);
$timeWeeks = round($timeDays / 7);
$timeMonths = round($timeWeeks / 4);
$timeYears = round($timeMonths / 12);
if($timeSeconds < '2') {
return ''.$timeSeconds.' second ago';
} elseif($timeSeconds < '60') {
return ''.$timeSeconds.' seconds ago';
} elseif($timeMinutes < '2') {
return ''.$timeMinutes.' minute ago';
} elseif($timeMinutes < '60') {
return ''.$timeMinutes.' minutes ago';
} elseif($timeHours < '2') {
return ''.$timeHours.' hour ago';
} elseif($timeHours < '24') {
return ''.$timeHours.' hours ago';
} elseif($timeDays < '2') {
return ''.$timeDays.' day ago';
} elseif($timeDays < '7') {
return ''.$timeDays.' days ago';
} elseif($timeWeeks < '2') {
return ''.$timeWeeks.' week ago';
} elseif($timeWeeks < '4') {
return ''.$timeWeeks.' weeks ago';
} elseif($timeMonths < '2') {
return ''.$timeMonths.' month ago';
} elseif($timeMonths < '12') {
return ''.$timeMonths.' months ago';
} elseif($timeYears < '2') {
return ''.$timeYears.' year ago';
} elseif($timeYears > '1') {
return ''.$timeYears.' years ago';
} else {
return $timeSeconds;
}
} else {
return 'The Future';
}
}
Because your calculations are messed up. See one example and check all your formulas
<?
//same numbers, different formula
$checkTime=0;
echo (time()-$checkTime)/31536000; //45.094949422882 Years
?>
31536000 is the number of seconds in 1 year.
Even using that you will have to take care about leap years. We cant divide a timestamp by minutes then by hours then by days and so on. If you need accurate results the input has to be accurate as well.
Remember the famous Bi-Weekly and Twice Monthly payouts used commonly in USA? From a distance they both appear to mean the same thing but they don't. So dividing like your code is doing looses all that accuracy and when that difference is multiplied to 45 years it becomes substantial.
Fiddle

Convert datetime into time ago [closed]

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.

calculate time difference like facebook messaging system [duplicate]

This question already has answers here:
Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...
(32 answers)
Closed 9 years ago.
I need to find time difference for like in facebook messages using php.
like: 2 weeks ago, 2 hr 30 mins ago, one second ago
My time format is "Y-m-d H:i:s"
Can Anyone help me with it?
Store the message created time in database then use below function :
function get_time_difference_php($created_time)
{
date_default_timezone_set('Asia/Calcutta'); //Change as per your default time
$str = strtotime($created_time);
$today = strtotime(date('Y-m-d H:i:s'));
// It returns the time difference in Seconds...
$time_differnce = $today-$str;
// To Calculate the time difference in Years...
$years = 60*60*24*365;
// To Calculate the time difference in Months...
$months = 60*60*24*30;
// To Calculate the time difference in Days...
$days = 60*60*24;
// To Calculate the time difference in Hours...
$hours = 60*60;
// To Calculate the time difference in Minutes...
$minutes = 60;
if(intval($time_differnce/$years) > 1)
{
return intval($time_differnce/$years)." years ago";
}else if(intval($time_differnce/$years) > 0)
{
return intval($time_differnce/$years)." year ago";
}else if(intval($time_differnce/$months) > 1)
{
return intval($time_differnce/$months)." months ago";
}else if(intval(($time_differnce/$months)) > 0)
{
return intval(($time_differnce/$months))." month ago";
}else if(intval(($time_differnce/$days)) > 1)
{
return intval(($time_differnce/$days))." days ago";
}else if (intval(($time_differnce/$days)) > 0)
{
return intval(($time_differnce/$days))." day ago";
}else if (intval(($time_differnce/$hours)) > 1)
{
return intval(($time_differnce/$hours))." hours ago";
}else if (intval(($time_differnce/$hours)) > 0)
{
return intval(($time_differnce/$hours))." hour ago";
}else if (intval(($time_differnce/$minutes)) > 1)
{
return intval(($time_differnce/$minutes))." minutes ago";
}else if (intval(($time_differnce/$minutes)) > 0)
{
return intval(($time_differnce/$minutes))." minute ago";
}else if (intval(($time_differnce)) > 1)
{
return intval(($time_differnce))." seconds ago";
}else
{
return "few seconds ago";
}
}

How do I check if something was 4 days ago in PHP?

I am trying to write a function which checks if a "Finished Lesson" was four days ago. How do I check if said lesson was in that time range, for example. If it was finished yesterday, 2 days ago, 3 days ago, 4 days ago, it would be true since it is in the time range of "4 days ago".
How do I check this?
So far I've done:
$time = time();
$fourDays = 345600;
$threeDays = 259200;
$lastLesson = $ml->getLesson($cid, $time, true);
$lastLessonDate = $lastLesson['deadline'];
$displayLastLesson = false;
if ($lastLessonDate + $fourDays < $time)
{
$displayLastLesson = true;
//We print lesson that was finished less than 4 days ago
}
else
{
//We print lesson that is in the next 3 days
}
Right now, the if statement keeps hitting true which is not what I want since I have a lesson that was finished on the 3rd May. It should be true for a lesson that was finished on the 7th May I guess?
$time = time();
$fourDays = strtotime('-4 days');
$lastLesson = $ml->getLesson($cid, $time, true);
$lastLessonDate = $finishedLesson['deadline'];
$displayLastLesson = false;
if ($lastLessonDate >= $fourDays && $lastLessonDate <= $time)
{
$displayLastLesson = true;
//We print lesson that was finished less than 4 days ago
}
else
{
//We print lesson that is in the next 3 days
}
All calculations should be calculated relative to today at 12am, not time() which gives you the current time now (e.g. 6pm) This is an issue because when you do this, 1 day ago (now - 24hours) means time that is between yesterday 6pm and today 6pm. Instead, yesterday should mean a time between yesterday 12am and today 12am.
Below is a simplified calculation to illustrate the idea:
$lastLessonDate = strtotime($lastLessonDate);
$today = strtotime(date('Y-m-d')); // 12:00am today , you can use strtotime('today') too
$day = 24* 60 * 60;
if($lastLessonDate > $today) // last lesson is more than 12:00am today, meaning today
echo 'today';
else if($lastLessonDate > ($today - (1 * $day))
echo 'yesterday';
else if($lastLessonDate > ($today - (2 * $day))
echo '2 days ago';
else if($lastLessonDate > ($today - (3 * $day))
echo '3 days ago';
else if($lastLessonDate > ($today - (4 * $day))
echo '4 days ago';
else
echo 'more than 4 days ago';

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.

Categories