Convert DateTime object to friendly time display
Convert DateTime objects to friendly time display using DateInterval in PHP 5.x
- /**
- * Friendly date and time
- *
- * @ Param DateTime $ datetime date and time
- * @ Param int $ size precise to the number of digits
- * @ Throws \ InvalidArgumentException
- * @ Return string
- */
- Function friendly_date ($ datetime, $ size = 1)
- {
- If (is_int ($ datetime )){
- $ Datetime = new \ DateTime ($ datetime );
- }
-
- If (! ($ Datetime instanceof \ DateTime )){
- Throw new \ InvalidArgumentException ('invalid "DateTime" object ');
- }
-
- $ Now = new \ DateTime ();
- $ Interval = $ now-> diff ($ datetime );
-
- $ IntervalData = array (
- $ Interval-> y, $ interval-> m, $ interval-> d,
- $ Interval-> h, $ interval-> I, $ interval-> s,
- );
- $ IntervalFormat = array ('year', 'month', 'day', 'Hourly ', 'specificity', 'second ');
-
- Foreach ($ intervalData as $ index => $ value ){
- If ($ value ){
- $ IntervalData [$ index] = $ value. $ intervalFormat [$ index];
- } Else {
- Unset ($ intervalData [$ index]);
- Unset ($ intervalFormat [$ index]);
- }
- }
-
- Return implode ('', array_slice ($ intervalData, 0, $ size ));
- }
|