Grow your CSS skills. Land your dream job.

Displaying a date difference

  • # February 17, 2013 at 11:37 am

    Hello beautiful people.

    I’m searching for a way to display a difference between two dates using PHP. I want it to output “X days ago” whereas the X will be the number.

    I have an array where I put the date:


    < ?php
    $pictures = array(
    array(
    'title' => "Mount Everest",
    'filename' => "everest.jpg",
    'upload_date' => "14-02-2013"
    )
    );
    ?>

    I want to target the ‘upload_date’ and find the difference between that date and now. I was thinking that I could do something like this:


    $today = time(); // Get the current time
    $uploaded = strtotime($pictures); // Convert the date to a timestamp

    $days_ago = ($today - $uploaded) / 60 / 60 / 24; // Subtract the date from the current time and display as days

    … but it turns out that there is an Undefined index: upload_date. I just can’t seem to figure out what’s wrong with the code.

    Thanks in advance,
    Kralle

    # February 18, 2013 at 1:34 pm

    I’m assuming you mean to have a “pictures” array that contains multiple “picture” arrays with the three data items you have as key value pairs.

    Your problem is twofold -
    1 ) You didn’t give the “picture” array a key name
    2) You aren’t feeding the array a proper multi-dimensional index.

    The below code worked for me, slightly commented.

    < ?php

    $pictures = array (
    ‘picture1′ => array ( // Add a key name for indexing
    ‘title’ => “Mount Everest”,
    ‘filename’ => “everest.jpg”,
    ‘upload_date’ => “12-02-2013″
    )
    );

    $today = time(); // Get the current time
    $uploaded = strtotime($pictures); // use the new key name to access a particular array + value

    $days_ago = ($today – $uploaded) / 60 / 60 / 24; // Subtract the date from the current time and display as days

    ?>

    Posted < ?php echo(floor($days_ago)); // Floor it out ot make it look nice?> days ago

    # February 20, 2013 at 6:13 pm

    Thanks a lot for your help, sir! That worked out pretty well.

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".