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

时间:2012-02-11 17:43:42

标签: php string date

我有以下字符串:

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

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

3 个答案:

答案 0 :(得分:2)

$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));

“Plano 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]);

答案 1 :(得分:1)

我想基于不常用的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

答案 2 :(得分:0)

// 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));