How do I format a list of dates from an array of unix timestamps?

A WordPress plugin that I’m using is outputting an array (which should be only two dates/times) that looks like this:

Array ( [0] => 1412037900 [1] => 1413340200 [2] => )

I’m not sure why there’s a trailing empty node but in any case, I’m trying to get a list of the formatted dates/times from this.

Read More

I have this in my php (the get_post_meta function is returning the array):

<?php global $post;
$date = get_post_meta( $post->ID, '_cmb2_date_time', true );
foreach ( $date as $item ) {
echo '<p>' . date("F j, Y, g:i a", (int)$item) . '</p>';
} ?>

Right now I’m getting this:

September 30, 2014, 12:45 am
October 15, 2014, 2:30 am
January 1, 1970, 12:00 am

And what I want is this:

September 30, 2014, 12:45 am
October 15, 2014, 2:30 am

Eventually I’d also like to make it conditional so that it echoes “TBA” when there are no dates. I can worry about that later once it’s working but at the moment when the array is empty I get an error that says “Warning: Invalid argument supplied for foreach()…”

Any help would be greatly appreciated!

Related posts

Leave a Reply

3 comments

  1. The last result is the datetime equivelant of 0 unix time, as you have an empty object at the end of the array. Simply remove (pop) the last object before converting like this:

    <?php global $post;
    $date = get_post_meta( $post->ID, '_cmb2_date_time', true );
    array_pop($date);
    foreach ( $date as $item ) {
    echo '<p>' . date("F j, Y, g:i a", (int)$item) . '</p>';
    } ?>
    

    Then, to include the TBA functionality:

    <?php global $post;
    $date = get_post_meta( $post->ID, '_cmb2_date_time', true );
    //If you are still getting an extra object even when there are no dates to be passed 
    //from get_post_meta then pop before the check if empty
    array_pop($date);
    if( empty( $date ) )
    {
         echo '<p>TBA</p>';
    }
    else
    {
        //If you are not getting the extra object when empty, only when there are results
        //then put the pop here before the foreach loop
        foreach ( $date as $item ) {
            echo '<p>' . date("F j, Y, g:i a", (int)$item) . '</p>';
        } 
    }
    ?>
    
  2. date() will output the current date and time if the final parameter is blank (or the unix epoch if 0), therefore use this code;

    foreach ( $date as $item ) {
        if($item) echo '<p>' . date("F j, Y, g:i a", (int)$item) . '</p>';
    }
    

    If the array entry is blank, no date will be echoed.

    Hope this helps.