Jesse
Jesse

Reputation: 45

Convert month numbers to letters PHP

I have this code to echo some records from a mysql database:

<?php
    $host = "localhost";
    $gebruikersnaam = "Admin";
    $wachtwoord = "Test123";
    mysql_connect($host, $gebruikersnaam, $wachtwoord);

    $database = "olf";
    mysql_select_db($database);

$result = mysql_query("SELECT * FROM agenda WHERE datum ORDER BY datum ASC LIMIT 0, 3");
while($row = mysql_fetch_array($result))
  {
?>
    <ul class="dates">
        <li>
        <span class="date"><?php echo "" .substr($row['datum'],5,2). "";?></strong></span>

        </li>

        <?php } ?>
        </ul>

In the database the format of the 'datum' (date) is YYYY-MM-DD, I echo just the part MM. So this is the format: 01 (January), 02 (February) etc. What I want:

If " .substr($row['datum'],5,2). " is equal to 01, then convert it to JAN

If " .substr($row['datum'],5,2). " is equal to 02, then convert it to FEB

If " .substr($row['datum'],5,2). " is equal to 03, then convert it to MAR

ETC..

How do I need to make this?

Upvotes: 1

Views: 154

Answers (3)

Erik
Erik

Reputation: 1057

Convert the incoming information to a DateTime object, then you can apply all sorts of fancy formatting rules:

$date = \DateTime::createFromFormat( "Y-m-d", $row['datum'] );
echo $date->format( 'M' ); // for just month in text
echo $date->format( 'D dS of F Y' ); // for example, "Monday 6th of November 2014"

Check out the workings of \DateTime on the php website:

https://www.php.net/manual/en/datetime.createfromformat.php

Upvotes: 0

Mureinik
Mureinik

Reputation: 311338

You shouldn't have to hassle with this yourself - let MySQL do the heavy lifting for you:

SELECT DATE_FORMAT (datum, '%b') AS month_abbreviation
FROM   agenda

Upvotes: 1

Jerodev
Jerodev

Reputation: 33186

Use the date function to display the date in a specific format.

In this case, M displays the three first letters of the months name.

echo date("M", strtotime($row['datum']));

Upvotes: 0

Related Questions