PHP:将日期字符串转换为Unix时间戳

24

给定以下字符串:

  • 01/01/11
  • 1/1/11
  • 1/1/2011
  • 01/1/2011
  • 1-1-2011
  • 等等

如何将它们转换为Unix时间戳。请注意,在大多数情况下,这将是以各种分隔符的dd mm yyyy格式。

3个回答

44

参考strtotimestrptime或者 DateTime 类。

strtotime示例:

$timestamp = strtotime('1/1/2011');
每个函数都有自己的注意点。例如,strtotime 的文档声明如下:
引号 如果分隔符是斜杠(/),则假设为美国的m/d/y格式;如果分隔符是破折号(-)或点号(.),则假设为欧洲的d-m-y格式。
您还可以使用preg_match捕获所有3部分并使用mktime创建自己的时间戳。 preg_match 示例:
if ( preg_match('/^(?P<day>\d+)[-\/](?P<month>\d+)[-\/](?P<year>\d+)$/', '1/1/2011', $matches) )
{
  $timestamp = mktime(0, 0, 0, ( $matches['month'] - 1 ), $matches['day'], $matches['year']);
}

您的正则表达式假定日期格式为 dd-mm-yyyy,但我不确定是否是这种格式。 - StackOverflowNewbie
@StackOverflowNewbie - 你的问题中提到:“请注意,大多数情况下,日期格式为dd mm yyyy,带有各种分隔符。” 所以我按照这个格式进行了处理,但你可以在原来的代码中添加elseif语句来检查不同的格式,并使regex更具体(例如,不使用\d+,而是使用描述月份0-12和日期0-31的模式)。当然,在1/2/13这种情况下,除非你知道格式,否则无法确定哪个是哪个。 - Francois Deschenes

5
$to='23.1.2014-18:16:35'
list($part1,$part2) = explode('-', $to);
list($day, $month, $year) = explode('.', $part1);
list($hours, $minutes,$seconds) = explode(':', $part2);
$timeto =  mktime($hours, $minutes, $seconds, $month, $day, $year);
echo $timeto;

2

您可能正在寻找strtotime函数

但是,请注意,它会将每个可能的字符串格式转换为Unix时间戳(纪元),因为很难明确解析每个日期时间字符串。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接