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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6501019/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:34:44  来源:igfitidea点击:

PHP: convert date string to Unix timestamp

php

提问by StackOverflowNewbie

Given the following strings:

给定以下字符串:

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

How do I convert these to a Unix timestamp. Note that in most cases, this will be in the format of dd mm yyyywith various delimiters.

如何将这些转换为 Unix 时间戳。请注意,在大多数情况下,这将采用dd mm yyyy带有各种分隔符的格式。

回答by Francois Deschenes

Look at strtotime, strptimeor the DateTimeclass.

看看strtotimestrptime还是DateTime上课。

strtotimeExample:

strtotime例子:

$timestamp = strtotime('1/1/2011');

Each function has it's caveat. For instance, the documentation for strtotimestates that:

每个功能都有它的警告。例如,文档strtotime说明:

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

m/d/y 或 dmy 格式的日期通过查看各个组件之间的分隔符来消除歧义:如果分隔符是斜杠 (/),则假定为美国 m/d/y;而如果分隔符是破折号 (-) 或点 (.),则假定为欧洲 dmy 格式。

You could also use preg_matchto capture all 3 parts and create your own timestamp using mktime.

您还可以使用preg_match捕获所有 3 个部分并使用mktime.

preg_matchExample:

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']);
}

回答by Lem

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

回答by anubhava

You're probably looking for strtotime function.

您可能正在寻找strtotime 函数

However just as a caution it will convert each and every possible string format to a unix timestamp (epoch) since it is very difficult to unambiguously parse each and every string to date-time.

然而,作为一个警告,它会将每个可能的字符串格式转换为 unix 时间戳(纪元),因为很难明确地将每个字符串解析为日期时间。