Melanie Sumner
Melanie Sumner

Reputation: 180

format time in php when results are from a loop

I have an event agenda set up to populate from a database, echoing rows from a loop.

I see how to format to get the time that I want: date("g:i a") BUT I can't seem to make it work within my php code.

I'm having the loop print the data to a $row, and then specifying which piece of data like this:

    <td>' .$row['start_time'] . '</td>

In which start_time is the column in my database that is the datetime piece of data.

I've tried a few different ways of adding in the formatting for the date time, but none of them have successfully returned results. How do I format this code so it will show up? Do I make it a function or can I add it to the line I have here?

I'd like to just return the time (not the date), and have it be something like 7:00am.

Thank you!

Edit to add: Here is more code that may shed light on where I'm struggling:

   $conn = new DatabaseConn();

   $query = "SELECT * FROM agenda WHERE date=\"2012-10-21\" AND visible=\"1\" ORDER BY agenda_id;";

   $result = mysql_query($query);

   if($result){

    $numfields = mysql_num_fields($result);
    $data = array();
    $flist = array();

        for($i=0;$i<$numfields;$i++)$flist[] = mysql_field_name($result,$i);
        $data[0] = $flist;
        while($row = mysql_fetch_assoc($result)){

         $data[] = $row;
         echo '
         <tr>
          <td id="time">'. $row['start_time']) . '</td>
          <td id="time">' . $row['end_time'] . '</td>   
          <td id="title">' . $row['title'] . '</td>
          <td id="description">' . $row['description'] . '</td>
          <td id="room">' . $row['room'] . '</td>
          <td id="type">' . $row['attendee_type'] . '</td>          
         </tr>
         ';
        }

Edit #2 to add: Here's my output on the test page: (copied the view source instead of just the page)

    <tr>
     <td id="time">2012-10-21 14:00:00 </td>
     <td id="time">2012-10-21 20:00:00</td>
     <td id="title">Registration</td>
     <td id="description">Open registration and conference check-in.</td>
     <td id="room">Lobby</td>
     <td id="type">all</td>
    </tr>                   

Upvotes: 1

Views: 502

Answers (2)

abhshkdz
abhshkdz

Reputation: 6365

Use this

echo date("g:i a", $row['start_time']); //$row['start_time'] should be Unix timestamp

Otherwise use

echo date("g:i a", strtotime($row['start_time'])); 

strtotime parses English textual datetime description into a Unix timestamp

Go through this to know about all date format characters.

Upvotes: 4

Constantin
Constantin

Reputation: 2318

date('g:i a', strtotime($row['start_time'])); // if $row['start_time'] is a valid timestamp

Upvotes: 0

Related Questions