将月份数字转换为字母PHP

时间:2014-10-23 07:15:22

标签: php

我有这段代码来回应mysql数据库中的一些记录:

<?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>

在数据库中,&#39;数据的格式为&#39; (日期)是YYYY-MM-DD,我只回应MM的部分。所以这是格式:01(1月),02(2月)等我想要的:

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 ..

我该如何制作?

3 个答案:

答案 0 :(得分:1)

你自己不应该为此烦恼 - 让MySQL为你做繁重的工作:

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

答案 1 :(得分:0)

使用date功能以特定格式显示日期。

在这种情况下,M会显示月份名称的三个首字母。

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

答案 2 :(得分:0)

将传入信息转换为DateTime对象,然后您可以应用各种奇特的格式规则:

$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"

查看php网站上\ DateTime的工作原理:

http://nl1.php.net/manual/en/datetime.createfromformat.php