18

根据标题:如何在 PHP 中将字符串日期(YYYY-MM-DD)转换为纪元(自 01-01-1970 以来的秒数)

4

4 回答 4

31

也许这回答了你的问题

http://www.epochconverter.com/programming/functions-php.php

以下是链接的内容:

有很多选择:

  1. 使用'strtotime':

strtotime 将大多数英语日期文本解析为纪元/Unix 时间。

echo strtotime("15 November 2012");
// ... or ...
echo strtotime("2012/11/15");
// ... or ...
echo strtotime("+10 days"); // 10 days from now

检查转换是否成功很重要:

// PHP 5.1.0 or higher, earlier versions check: strtotime($string)) === -1
if ((strtotime("this is no date")) === false) {
   echo 'failed';
 }

2. 使用 DateTime 类:

PHP 5 DateTime 类更好用:

// object oriented
$date = new DateTime('01/15/2010'); // format: MM/DD/YYYY
echo $date->format('U'); 

// or procedural
$date = date_create('01/15/2010'); 
echo date_format($date, 'U');

日期格式“U”将日期转换为 UNIX 时间戳。

  1. 使用“mktime”:

这个版本比较麻烦,但适用于任何 PHP 版本。

// PHP 5.1+ 
date_default_timezone_set('UTC');  // optional 
mktime ( $hour, $minute, $second, $month, $day, $year );

// before PHP 5.1
mktime ( $hour, $minute, $second, $month, $day, $year, $is_dst );
// $is_dst : 1 = daylight savings time (DST), 0 = no DST ,  -1 (default) = auto

// example: generate epoch for Jan 1, 2000 (all PHP versions)
echo mktime(0, 0, 0, 1, 1, 2000); 
于 2013-03-13T08:52:07.800 回答
10

试试这个 :

$date  = '2013-03-13';

$dt   = new DateTime($date);
echo $dt->getTimestamp();

参考:http ://www.php.net/manual/en/datetime.gettimestamp.php

于 2013-03-13T08:52:57.687 回答
2

使用strtotime()它为您提供从 01-01-1970 开始的 Unix 时间戳

于 2013-03-13T08:52:30.373 回答
2

使用strtotime()函数:

strtotime('2013-03-13');
于 2013-03-13T08:53:19.980 回答