如何在 PHP 中将日期 YYYY-MM-DD 转换为纪元
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15380599/
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
How to convert a date YYYY-MM-DD to epoch in PHP
提问by Gianluca Ghettini
As per title: how to convert a string date (YYYY-MM-DD) to epoch (seconds since 01-01-1970) in PHP
根据标题:如何在 PHP 中将字符串日期 (YYYY-MM-DD) 转换为纪元(自 01-01-1970 以来的秒数)
回答by Nick Audenaerde
Perhaps this answers your question
也许这回答了你的问题
http://www.epochconverter.com/programming/functions-php.php
http://www.epochconverter.com/programming/functions-php.php
Here is the content of the link:
以下是链接的内容:
There are many options:
有很多选择:
- Using 'strtotime':
- 使用“strtotime”:
strtotime parses most English language date texts to epoch/Unix Time.
strtotime 将大多数英语日期文本解析为纪元/Unix 时间。
echo strtotime("15 November 2012");
// ... or ...
echo strtotime("2012/11/15");
// ... or ...
echo strtotime("+10 days"); // 10 days from now
It's important to check if the conversion was successful:
检查转换是否成功很重要:
// PHP 5.1.0 or higher, earlier versions check: strtotime($string)) === -1
if ((strtotime("this is no date")) === false) {
echo 'failed';
}
2. Using the DateTime class:
2. 使用 DateTime 类:
The PHP 5 DateTime class is nicer to use:
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');
The date format 'U' converts the date to a UNIX timestamp.
日期格式“U”将日期转换为 UNIX 时间戳。
- Using 'mktime':
- 使用“mktime”:
This version is more of a hassle but works on any PHP version.
这个版本比较麻烦,但适用于任何 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);
回答by Prasanth Bendra
Try this :
尝试这个 :
$date = '2013-03-13';
$dt = new DateTime($date);
echo $dt->getTimestamp();
回答by Michal M
回答by Rohit Kumar Choudhary
use strtotime()it provides you Unix time stamp starting from 01-01-1970
使用strtotime()它为您提供从 01-01-1970 开始的 Unix 时间戳

