0

Hi all,

I've been trying to create a friendly time function for a while, it's purpose should be quite obiovus from the code below. Currently, it outputs "expired" for everything.

I am so utterly confused from visualising the code and trying to figure out where the times lie in relation to each other, so I would really appreciate if some good soul could come along and make any suggestions.

public function generateFriendlyTime($time)
    {
        if(!is_numeric($time))
        {
            $time = strtotime($time);
        }

        $current_time = time();


        if($time < $current_time)
        {
            return 'expired';
        }

        //If less than a minute
        elseif($time < ($current_time + 60))
        {
            return "< " . 1 . "m";
        }

        //If less than an hour
        elseif($time < ($current_time + 3600))
        {
            return round(($time - $current_time) / 60) . "mins";
        }

        //If less than a day
        elseif($time < ($current_time + 86400))
        {
            return round(($time - $current_time) / 3600) . "h";
        }

        //If less than a week
        elseif($time <= ($current_time + 604800))
        {
            return round(($time - $current_time) / 86400) . "d";
        }

        //If less than a month
        elseif($current_time > 604800)
        {
            return round(($time - $current_time) / 604800) . "w";
        }

        else
        {
            return date('j F h:ia', $time);
        }
    }   
2
Contributors
2
Replies
14
Views
1 Year
Discussion Span
Last Post by James_43
3

Have you tried with DateTime?

<?php

$one = '09:30 am';
$two = '11:00 AM';

$time1 = new Datetime($one);
$time2 = new Datetime($two);

$diff = $time1->diff($time2);

print_r($diff);

Which outputs a DateInterval object like this:

DateInterval Object
(
    [y] => 0
    [m] => 0
    [d] => 0
    [h] => 1
    [i] => 30
    [s] => 0
    [weekday] => 0
    [weekday_behavior] => 0
    [first_last_day_of] => 0
    [invert] => 0
    [days] => 0
    [special_type] => 0
    [special_amount] => 0
    [have_weekday_relative] => 0
    [have_special_relative] => 0
)

From there, then it should be easy to perform the statements. Docs:

Edited by cereal

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.