我有一组以下格式的日期字符串:
$date = 'month_name DD, YYYY';
我想做的是将月份名称缩短为 3 个字符,并从末尾删除年份,如下所示:
$output = 'June 10, 2012';
print $output // Outputs 'Jun 10';
到目前为止,我有以下内容,但尚未找到缩短第一个单词的方法:
print substr($date, 0, strrpos($date, ',')); // Outputs 'June 10';
任何帮助将不胜感激!
使用 PHP 的 DateTime 类:
$string = 'June 10, 2012';
$date = DateTime::createFromFormat('F d, Y', $string, new DateTimeZone('America/New_York'));
echo $date->format('M d'); // Output: Jun 10
这是在不同格式之间转换时间的一种非常稳定的方式。
演示
$tmp=explode(' ',$date);
$tmp=substr($tmp[0],0,3).' '.substr($tmp[1],-1);
echo $tmp;
$date = explode(" ", substr($date, 0, strrpos($date, ',')));
// first word is month, second is the date.
$date[0] = substr($date[0],0,3);
$date = join(" ", $date); // now date contains your desired result