使用PHP将字符串转换为格式化日期


Converting string to formatted date using PHP

我有以下字符串:

$str = "Tuesday, February 21 at 7:30am at Plano B";

at Plano B是可选的。我想将其转换为:TUE 21 FEB 07:30

$str = "Tuesday, February 21 at 7:30am at Plano B";
$time = strtotime(trim(substr($str,0,(strrpos("at"))));
echo "Date: " . strtoupper(date('D d M H:i', $time));

你说"在普莱诺B是可选的"是什么意思。有时有,有时没有?

否则:

$str = "Tuesday, February 21 at 7:30am at Plano B";
preg_match("/[a-z]+, ([a-z]+ [0-9]{1,2}) at ([0-9]{1,2}:[0-9]{1,2}[am|pm])/i", $str, $match);
$time = strtotime($match[1] + ' ' + $match[2]);
echo "Date: " . strtoupper(date('D d M H:i', $time));

它总是"Plano B"还是空的?或者它也可以是"Plano A"或完全不同的东西?

请参见此处:http://regexr.com?2vvuj

但是您在初始字符串中缺少年份,因此无法解析为strtotime。您还希望输出没有am/pm。。你想用24小时吗?

这不是一个好办法,但如果没有今年,我想我们别无选择。。

preg_match("/([a-z]+), ([a-z]+) ([0-9]{1,2}) at ([0-9]{1,2}:[0-9]{1,2})([am|pm])/i", $str, $match);
$day = substr($match[1], 0, 3);
$mon = substr($match[2], 0, 3);
echo strtoupper($day . " " . $match[3] . " " . $mon . " " . $match[4]);

我想基于不常用的strptime提出一个稍微不同的解决方案。它使用预定义的格式来解析字符串。

示例:

<?php
// Specify a default timezone just in case one isn't set in php.ini.
date_default_timezone_set('America/Vancouver');
$str = "Tuesday, February 21 at 7:30am at Plano B";
if ($time = strptime($str, '%A, %B %e at %l:%M%P')) {
    // This will default to the current year.
    echo strtoupper(date('D d M H:i', mktime($time['tm_hour'], $time['tm_min'], 0, $time['tm_mday'], $time['tm_mon'])));
}

输出:

SUN 01 SEP 07:30
// Strip the last at, if its not a time
if(!preg_match("/at [0-9]+:[0-9]+[ap]m$/", $str)) {
  $str = preg_replace("/at [^0-9].*/","",$str);
}
// Then convert to time
$time = strtotime($str);
// Then output in specified format
echo strtoupper(date("D d M h:i", $time));