PHP:将日期字符串转换为Unix时间戳 [英] PHP: convert date string to Unix timestamp

查看:161
本文介绍了PHP:将日期字符串转换为Unix时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下字符串:

  • 01/01/11
  • 1/1/11
  • 2011年1月1日
  • 2011年1月1日
  • 2011年1月1日

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

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

推荐答案

查看 strtotime strptime DateTime 类.

Look at strtotime, strptime or the DateTime class.

strtotime示例:

strtotime Example:

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

每个功能都有它的警告.例如,strtotime的文档指出:

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

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

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.

您还可以使用 preg_match 来捕获全部3个部分,并使用 mktime 创建自己的时间戳.

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

preg_match示例:

preg_match Example:

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

这篇关于PHP:将日期字符串转换为Unix时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆