I am trying to convert a number on minutes into number of days using Carbon.
$minutes = 1400;
I want to do something like below (which of course, does not work):
Carbon->minutes($minutes)->days();
I cannot find an example of this. Thanks for any help.
Not tested, but a quick look at the docs suggests it might be aimed more at DateTime objects than differences in time, so you could do something like this:
$now = Carbon::now();
$days = $now->diffInDays($now->copy()->addMinutes($minutes));
Maybe CarbonInterval::minutes($minutes)->cascade();?
Will cascade down your value and format it for humans.
If you want to convert seconds to Jira style 1y 1m 1w 1h 1m 1s:
class Translator implements TranslatorInterface, TranslatorBagInterface
{
protected const TRANS = [
'year' => 'y',
'month' => 'm',
'week' => 'w',
'day' => 'd',
'hour' => 'h',
'minute' => 'm',
'second' => 's',
];
public function trans(string $id, array $parameters = [], string $domain = null, string $locale = null)
{
return $parameters[':count'].self::TRANS[$id];
}
public function getCatalogue(string $locale = null)
{
return new \Symfony\Component\Translation\MessageCatalogue('pl_PL');
}
}
$second = 1;
$minute = 60 * $second;
$hours = 60 * $minute;
$day = 24 * $hours;
$week = 7 * $day;
$month = 4 * $week;
$year = 12 * $month;
$sum = $second + $minute + $hours + $day + $week + $month + $year;
$interval = CarbonInterval::seconds($sum)->cascade();
$interval->setLocalTranslator(new Translator());
echo $interval->forHumans(); // 1y 1m 1w 1h 1m 1s
if you want to convert to years, months, weeks, days, hours, minutes, seconds, microseconds
use Carbon\CarbonInterval;
echo CarbonInterval::minutes(2212)->cascade()->forHumans();
//output = 1 day 12 hours 52 minutes
Related
I can do it for days like this:
$d1 = new DateTime('2000-01-01 12:00:00');
$d2 = new DateTime('2020-01-01 12:00:00');
$diff = $d2->diff($d1);
echo $diff->days;
In other words, it works for days. However, the DateTime/DateInterval class has only a $days variable -- these are expected but don't exist:
$diff->weeks;
$diff->months;
$diff->years;
Reading the manual, you might at first glance be deceived into thinking that it does have these attributes: https://www.php.net/manual/en/class.dateinterval.php
public integer $y ;
public integer $m ;
public integer $d ;
public integer $h ;
public integer $i ;
public integer $s ;
public float $f ;
public integer $invert ;
public mixed $days ;
The y, m, d, h, i, s there are not "individual totals", but depend on each other. For example, if the time span is exactly one year, the $y will be 1, but all of the other ones will be 0, instead of their respective representations (12 months, 52 weeks, etc.).
They treat days specially for some reason by including the $days variable, which does show the actual total number of days. I want that for weeks, months and years too.
I already know how to "estimate" the number of weeks/months/years between two timestamps, by using simple math and fixed variables representing the average number of seconds in each time unit. Since this doesn't take into consideration all the complexities of "traversing" the calendar format(s), such as leap years, varying days in different months, and many other small/complex details, you don't get the exact number that way.
I want to know the exact total number of weeks between two timestamps, and the same thing for years and months, independent of each other.
This will return the exact difference between two days hope this will help you.
$time_diffrence=getDiffrenceBetweenTwoDays($date1,$date2);
function getDiffrenceBetweenTwoDays($date1,$date2){
$etime = strtotime($date1) - strtotime($date2;
if ($etime < 1)
{
return '0 seconds';
}
$a = array( 365 * 24 * 60 * 60 => 'year',
30 * 24 * 60 * 60 => 'month',
24 * 60 * 60 => 'day',
60 * 60 => 'hour',
60 => 'minute',
1 => 'second'
);
$a_plural = array( 'year' => 'years',
'month' => 'months',
'day' => 'days',
'hour' => 'hours',
'minute' => 'minutes',
'second' => 'seconds'
);
foreach ($a as $secs => $str)
{
$d = $etime / $secs;
if ($d >= 1)
{
$r = round($d);
return $r . ' ' . ($r > 1 ? $a_plural[$str] : $str) .'' ;
}
}
}
Replace %a with any of the following at this link:
FORMATS
$d1 = date_create('2000-01-01 12:00:00');
$d2 = date_create('2020-01-01 12:00:00');
$diff = date_diff($d1, $d2);
$days = $diff->format('%a');
echo $days; // 7305
I have a function like this:
function time_elapsed_string($ptime)
{
$date_time = strtotime("1348-10-10 04:30:01") + $ptime;
$year = date("Y",$date_time);
$month = date("m",$date_time);
$day = date("d",$date_time);
$time = date("H:i:s",$date_time);
$etime = time() - $ptime + 1;
$a = array( 31536000 => 'year',
2592000 => 'month',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
);
foreach ($a as $secs => $str)
{
$d = $etime / $secs;
if ($d >= 1)
{
$r = round($d);
// EX:
return array('date' => $day.'-'.$month.'-'.$year, // 2016-02-20
'time' => $time, // 03:30:04
'difference' => $r . ' ' . $str . ' ago' // 2 month ago
);
}
}
}
And I use it like this:
$ptime = 1470692661;
$html = '<span title="date: '.time_elapsed_string($ptime)['date'].' time: '.time_elapsed_string($ptime)['time'].'">in '.time_elapsed_string($ptime)['difference'].'<span>';
As you see, I'm using of that function's result like this:
time_elapsed_string($ptime)['date']
ime_elapsed_string($ptime)['time']
time_elapsed_string($ptime)['difference']
In fact I'm calling that function every time I need one of its results. Is that right? Or should I call it once and store it into an array?
Note: My code works as well.
Counting time elapsed since some date/time like this is mauvais ton.
DateTime has been available since PHP 5.2.0 and tonns of people underestimate it. Why don't you use this instead of loops and ifs?
$create_time = "2016-08-02 12:35:04";
$current_time="2016-08-02 16:16:02";
$dtCurrent = DateTime::createFromFormat('Y-m-d H:i:s', $current_time);
// to use current timestamp, use the following:
//$dtCurrent = new DateTime();
$dtCreate = DateTime::createFromFormat('Y-m-d H:i:s', $create_time);
$diff = $dtCurrent->diff($dtCreate);
Now, you can format the result however you want:
$interval = $diff->format("%h hours %i minutes %s seconds");
This will give a clean 3 hours 40 minutes 58 seconds without any arrays, which is better.
UPDATE
There is a general solution to get hours / minutes / seconds via regex:
$interval = $diff->format("%y years %m months %d days %h hours %i minutes %s seconds");
// now remove zero values
$interval = preg_replace('/(^0| 0) (years|months|days|hours|minutes|seconds)/', '', $interval);
UPDATE 2
As of your comment:
Look, I want to use your approach .. but I really cannot implement it .. Actually I need three things: time, date, difference ..! But your approach doesn't give me them..
Well, we already know how to get the difference, it's the $interval variable described above.
To get time and date, you can get it from the $dtCreate variable by, again, using format:
$time = $dtCreate->format('H:i:s');
$date = $dtCreate->format('d-m-Y');
This is a no brainer.
Yes - store the function call result of time_elapsed_string($ptime) in an array, then use that to access your results. You're wasting CPU cycles otherwise!
// call it once
$result = time_elapsed_string($ptime);
// then use:
$result['date'];
$result['time'];
$result['difference'];
I am trying to transform a unix timestamp into a human readable string so i can show how long ago a user signed up.
Here is my data:
mysql> select createdate as unixtimestamp,date_format(from_unixtime(createdate),'%e %b %Y') as dateformatted from users where userid=40645;
+---------------+---------------+
| unixtimestamp | dateformatted |
+---------------+---------------+
| 1162642968 | 4 Nov 2006 |
+---------------+---------------+
1 row in set (0.00 sec)
mysql>
Ok so here is where the problem resides. I found 3 different functions on the internet that return a human readable string from a unix timestamp. All 3 failed to work.
I'd like someone to look at these functions and help me figure out how to fix one of them to return the correct human readable string.
On with the show!
Here is function #1:
function getElapstedTimeHumanReadable($time)
{
$names = array("seconds", "minutes", "hours", "days", "months", "years");
$values = array(1, 60, 3600, 24 * 3600, 30 * 24 * 3600, 365 * 24 * 3600);
$time = time()-$time;
for($i = count($values) - 1; $i > 0 && $time < $values[$i]; $i--);
if($i == 0) {
$timestamp = intval($time / $values[$i]) . " " . $names[$i];
} else {
$t1 = intval($time / $values[$i]);
$t2 = intval(($time - $t1 * $values[$i]) / $values[$i - 1]);
$timestamp= "$t1 " . $names[$i] . ", $t2 " . $names[$i - 1];
}
return $timestamp;
}
My return value for this function is "Joined 1 days, 17 hours ago"
Clearly this isn't correct.
Here is function #2:
function getElapsedTimeHumanReadable($time)
{
$time = time() - $time;
$points = array(
'year' => 31556926,
'month' => 2629743,
'week' => 604800,
'day' => 86400,
'hour' => 3600,
'minute' => 60,
'second' => 1
);
foreach($points as $point => $value)
{
if($elapsed = floor($time/$value) > 0)
{
$s = $elapsed>1?'s':'';
$timestamp = "$elapsed $point$s";
break;
}
}
return $timestamp;
}
My return value for this function is "Joined 1 day ago
And finally, here is function #3:
function getElapsedTimeHumanReadable($time)
{
$etime=time()-$time;
if ($etime < 1)
{
return '0 seconds';
}
$a = array( 365 * 24 * 60 * 60 => 'year',
30 * 24 * 60 * 60 => 'month',
24 * 60 * 60 => 'day',
60 * 60 => 'hour',
60 => 'minute',
1 => 'second'
);
$a_plural = array( 'year' => 'years',
'month' => 'months',
'day' => 'days',
'hour' => 'hours',
'minute' => 'minutes',
'second' => 'seconds'
);
foreach ($a as $secs => $str)
{
$d = $etime / $secs;
if ($d >= 1)
{
$r = round($d);
return $r . ' ' . ($r > 1 ? $a_plural[$str] : $str) . ' ago';
}
}
}
So theres my code and my data. Not quite sure why none seem to work. I tried looking at the code but I cannot figure out how to solve it.
Whats interesting is they all say 2 days, but my timestamp appears to show 2006.
Thanks for the help.
$time = 1162642968 ;
$date = new DateTime( );
$date->setTimestamp( $time );
$today = new DateTime( 'now', new DateTimeZone( "Europe/Rome" ) );
$diff = $today->diff( $date);
echo "Year: " . $diff->y . " - Month: " . $diff->m . " - Days: " . $diff->d . " - Hours: " . $diff->h;
EXAMPLE
As suggested I'll add explanation, even if I think it is really self explain.
$date = new DateTime() create the object and $date->setTimestamp( $time ) is used to put that date at a value from the mysql timestamp.
$today is created pointing at the actual date.
$date->diff() create a DateInterval Object ( http://php.net/manual/en/class.dateinterval.php ) that contains all the necessary datas.
If you want to solve this yourself, you should calculate the difference and base it on those values. I haven't tested RiccardoC's Answer, but this seems as a nice way to go.
As I see in your posting, you calculate a year always as 365 days, so if you don't want to go in a deep detail with time zones, extra hours, extra days, different month lengths etc, you could use something simple as that:
function getElapsedTimeHumanReadable($timestamp) {
$diff = time() - $timestamp;
$years = intval($diff/31536000); //seconds in a year 60*60*24*365
$diff -= ($years*31536000);
$months = intval($diff/2592000); //seconds in a month 60*60*24*30
$diff -= ($months*2592000);
$days = intval($diff/86400); //seconds in a day 60*60*24
return $years." years, ".$months." months, ".$days." days ago";
}
echo getElapsedTimeHumanReadable(1162642968); // November 4th, 2006
Echos 9 years, 0 months, 17 days ago
im trying to convert a mysql timestamp to time in months or days or hours or minutes.
so the output will look like this:
added 1 month ago / added: 0 hours ago / added: 21 minutes ago / added 30 seconds ago
so i only want one format of time depending on how many minutes or how many hours or how many days etc, so 60 minutes converts to 1 hour ago or 24 hours converts to 1 day ago and 48 hours converts to 2 dayS ago.
so far i have this code:
<?
$datetime1 = new DateTime();
$datetime2 = new DateTime ($news['date_added']);
$interval = $datetime1->diff($datetime2);
str_replace('0 hours', '', $variable);
echo $interval->format('%h hours %i minutes');
?>
and this outputs the following:
added 0 hours ago 57 minutes ago.
can someone help me or show me what id need to do in order to get the formats to display right, im really new to php and am not sure how i can do this. thank you.
From http://php.net/manual/en/ref.datetime.php
Just change $precision to 1 when you call the function and add in whatever text you want to come before and after the date. You'll have to make sure you convert your date objects to timestamps, but that shouldn't be a problem for you.
/**
* this code assumes php >= 5.1.0. if using < 5.1, read
* php.net/strtotime and change the condition for checking
* for failure from strtotime()
*/
// $t1, $t2: unix times, or strtotime parseable
// $precision: max number of units to output
// $abbr: if true, use "hr" instead of "hour", etc.
function date_diff ($t1, $t2, $precision = 6, $abbr = false) {
if (preg_match('/\D/', $t1) && ($t1 = strtotime($t1)) === false)
return false;
if (preg_match('/\D/', $t2) && ($t2 = strtotime($t2)) === false)
return false;
if ($t1 > $t2)
list($t1, $t2) = array($t2, $t1);
$diffs = array(
'year' => 0, 'month' => 0, 'day' => 0,
'hour' => 0, 'minute' => 0, 'second' => 0,
);
$abbrs = array(
'year' => 'yr', 'month' => 'mth', 'day' => 'day',
'hour' => 'hr', 'minute' => 'min', 'second' => 'sec'
);
foreach (array_keys($diffs) as $interval) {
while ($t2 >= ($t3 = strtotime("+1 ${interval}", $t1))) {
$t1 = $t3;
++$diffs[$interval];
}
}
$stack = array();
foreach ($diffs as $interval => $num)
$stack[] = array($num, ($abbr ? $abbrs[$interval] : $interval) . ($num != 1 ? 's' : ''));
$ret = array();
while (count($ret) < $precision && ($item = array_shift($stack)) !== null) {
if ($item[0] > 0)
$ret[] = "{$item[0]} {$item[1]}";
}
return implode(', ', $ret);
}
$t1 = 'Feb 4, 2008 12:16:00';
$t2 = 'Jul 3, 2006 16:15:30';
echo date_diff($t1, $t2), "\n",
date_diff($t1, $t2, 3), "\n",
date_diff($t1, $t2, 2, true), "\n";
?>
Here is a possible solution. You format the time difference as a string with months-days-hours-minutes-seconds, then look through that string for the first non-zero number: that's the one you want...
$mdhms = explode('-',$interval->format('%m-%d-%H-%i-%s'));
$labels = Array(' months', ' days', ' hours', ' minutes', ' seconds');
$i = 0;
foreach($mdhms as $t){
if($t > 0) break;
$i+=1;
}
if ($i < 5) echo "It happened ".$t.$labels[$i]." ago";
else echo "It is happening right now!"
I'm trying to work with dates for the first time, I did it something about that with Flash but it's different.
I have two different dates and I'd like to see the difference in hours and days with them, I've found too many examples but not what I'm loking for:
<?php
$now_date = strtotime (date ('Y-m-d H:i:s')); // the current date
$key_date = strtotime (date ("2009-11-21 14:08:42"));
print date ($now_date - $key_date);
// it returns an integer like 5813, 5814, 5815, etc... (I presume they are seconds)
?>
How can I convert it to hours or to days?
The DateTime diff function returns a DateInterval object. This object consists of variabeles related to the difference. You can query the days, hours, minutes, seconds just like in the example above.
Example:
<?php
$dateObject = new DateTime(); // No arguments means 'now'
$otherDateObject = new DateTime('2008-08-14 03:14:15');
$diffObject = $dateObject->diff($otherDateObject));
echo "Days of difference: ". $diffObject->days;
?>
See the manual about DateTime.
Sadly, it's a PHP 5.3> only feature.
Well, you can always use date_diff, but that is only for PHP 5.3.0+
The alternative would be math.
How can I convert it [seconds] to hours or to days?
There are 60 seconds per minute, which means there are 3600 seconds per hour.
$hours = $seconds/3600;
And, of course, if you need days ...
$days = $hours/24;
If you dont have PHP5.3 you could use this method from userland (taken from WebDeveloper.com)
function date_time_diff($start, $end, $date_only = true) // $start and $end as timestamps
{
if ($start < $end) {
list($end, $start) = array($start, $end);
}
$result = array('years' => 0, 'months' => 0, 'days' => 0);
if (!$date_only) {
$result = array_merge($result, array('hours' => 0, 'minutes' => 0, 'seconds' => 0));
}
foreach ($result as $period => $value) {
while (($start = strtotime('-1 ' . $period, $start)) >= $end) {
$result[$period]++;
}
$start = strtotime('+1 ' . $period, $start);
}
return $result;
}
$date_1 = strtotime('2005-07-31');
$date_2 = time();
$diff = date_time_diff($date_1, $date_2);
foreach ($diff as $key => $val) {
echo $val . ' ' . $key . ' ';
}
// Displays:
// 3 years 4 months 11 days
TheGrandWazoo mentioned a method for php 5.3>. For lower versions you can devide the number of seconds between the two dates with the number of seconds in a day to find the number of days.
For days, you do:
$days = floor(($now_date - $key_date) / (60 * 60 * 24))
If you want to know how many hours are still left, you can use the modulo operator (%)
$hours = floor((($now_date - $key_date) % * (60 * 60 * 24)) / 60 * 60)
<?php
$now_date = strtotime (date ('Y-m-d H:i:s')); // the current date
$key_date = strtotime (date ("2009-11-21 14:08:42"));
$diff = $now_date - $key_date;
$days = floor($diff/(60*60*24));
$hours = floor(($diff-($days*60*60*24))/(60*60));
print $days." ".$hours." difference";
?>
I prefer to use epoch/unix time deltas. Time represented in seconds and as such you can very quickly divide by 3600 for hours and divide by 24*3600=86400 for days.