格式化日期输出 - PHP

imc*_*ell 1 php date

我正在使用以下内容

<?php
function custom_echo($x)
{
  if(strlen($x)<=150)
  {
    echo $x;
  }
  else
  {
    $y=substr($x,0,150) . '...';
    echo $y;
  }
}

// Include the wp-load'er
include('../../blog/wp-load.php');

// Get the last 10 posts
// Returns posts as arrays instead of get_posts' objects
$recent_posts = wp_get_recent_posts(array(
  'numberposts' => 4
));

// Do something with them
echo '<div>';
foreach($recent_posts as $post) {
  echo '<a class="blog-title" href="', get_permalink($post['ID']), '">', $post['post_title'], '</a><br />', $post['post_date'], custom_echo($post['post_content']), '<br /><br />';
}
echo '</div>';
?>
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是$ post ['post_date'] - 它出现在2012-12-03 13:59:56 - 我只是希望这个读到2012年12月3日.我不知道怎么去关于它.我知道还有其他类似的解决方案,但我是新手,并且真的不理解他们......?

救命?

谢谢.

koo*_*jah 8

在PHP中,该date()函数具有许多格式化可能性.你想要做的是使用这个声明:

echo date("F j, Y", $post['post_date']);
Run Code Online (Sandbox Code Playgroud)

这里

  1. 'F'对应于a full textual representation of a month, such as January or March
  2. 'j'对应于a Day of the month without leading zeros
  3. 'Y'对应于a A full numeric representation of a year, 4 digits

您可以在此处找到有关文档的更多信息和格式:http://php.net/manual/en/function.date.php

编辑:如果您的变量$post['post_date']包含现有日期,您应该这样做:

echo date("F j, Y", strtomtime($post['post_date']));
Run Code Online (Sandbox Code Playgroud)

该函数strtotime()将首先在时间戳中转换现有日期以date()使其正常工作.

更多信息请strtotime()访问:http://php.net/manual/en/function.strtotime.php

  • @ user1802256:尝试做`echo date("F j,Y",strtotime($ post ['post_date'])); (2认同)