如何在 PHP 中将日期转换为时间戳?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/113829/
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 date to timestamp in PHP?
提问by Wizard4U
How do I get timestamp from e.g. 22-09-2008?
我如何从例如获取时间戳22-09-2008?
回答by Owen
This method works on bothWindows and Unix andis time-zoneaware, which is probably what you want if you work with dates.
这种方法适用于这两个Windows和Unix和是时区意识到,这可能是你想要什么,如果你一起工作的日期。
If you don't care about timezone, or want to use the time zone your server uses:
如果您不关心时区,或者想使用您的服务器使用的时区:
$d = DateTime::createFromFormat('d-m-Y H:i:s', '22-09-2008 00:00:00');
if ($d === false) {
die("Incorrect date string");
} else {
echo $d->getTimestamp();
}
1222093324(This will differ depending on your server time zone...)
1222093324 (这会因您的服务器时区而异...)
If you want to specify in which time zone, here EST. (Same as New York.)
如果要指定在哪个时区,这里是 EST。(与纽约相同。)
$d = DateTime::createFromFormat(
'd-m-Y H:i:s',
'22-09-2008 00:00:00',
new DateTimeZone('EST')
);
if ($d === false) {
die("Incorrect date string");
} else {
echo $d->getTimestamp();
}
1222093305
1222093305
Or if you want to use UTC. (Same as "GMT".)
$d = DateTime::createFromFormat(
'd-m-Y H:i:s',
'22-09-2008 00:00:00',
new DateTimeZone('UTC')
);
if ($d === false) {
die("Incorrect date string");
} else {
echo $d->getTimestamp();
}
1222093289
1222093289
Regardless, it's always a good starting point to be strict when parsing strings into structured data. It can save awkward debugging in the future. Therefore I recommend to always specify date format.
无论如何,在将字符串解析为结构化数据时严格执行始终是一个很好的起点。可以省去以后麻烦的调试。因此我建议始终指定日期格式。
回答by Armin Ronacher
There is also strptime()which expects exactly one format:
还有strptime()只需要一种格式:
$a = strptime('22-09-2008', '%d-%m-%Y');
$timestamp = mktime(0, 0, 0, $a['tm_mon']+1, $a['tm_mday'], $a['tm_year']+1900);
回答by Gordon
With DateTimeAPI:
使用DateTimeAPI:
$dateTime = new DateTime('2008-09-22');
echo $dateTime->format('U');
// or
$date = new DateTime('2008-09-22');
echo $date->getTimestamp();
The same with the procedural API:
与程序 API 相同:
$date = date_create('2008-09-22');
echo date_format($date, 'U');
// or
$date = date_create('2008-09-22');
echo date_timestamp_get($date);
If the above fails because you are using a unsupported format, you can use
如果由于您使用的格式不受支持而导致上述操作失败,则可以使用
$date = DateTime::createFromFormat('!d-m-Y', '22-09-2008');
echo $dateTime->format('U');
// or
$date = date_parse_from_format('!d-m-Y', '22-09-2008');
echo date_format($date, 'U');
Note that if you do not set the !, the time portion will be set to current time, which is different from the first four which will use midnight when you omit the time.
请注意,如果不设置!,则时间部分将设置为当前时间,这与前四个省略时间时将使用午夜不同。
Yet another alternative is to use the IntlDateFormatterAPI:
另一种选择是使用IntlDateFormatterAPI:
$formatter = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'GMT',
IntlDateFormatter::GREGORIAN,
'dd-MM-yyyy'
);
echo $formatter->parse('22-09-2008');
Unless you are working with localized date strings, the easier choice is likely DateTime.
除非您使用本地化的日期字符串,否则更简单的选择可能是 DateTime。
回答by daremon
Be careful with functions like strtotime()that try to "guess" what you mean (it doesn't guess of course, the rules are here).
小心这样的函数strtotime()试图“猜测”你的意思(当然它不会猜测,规则在这里)。
Indeed 22-09-2008will be parsed as 22 September 2008, as it is the only reasonable thing.
Indeed22-09-2008将被解析为22 September 2008,因为它是唯一合理的事情。
How will 08-09-2008be parsed? Probably 09 August 2008.
将如何08-09-2008解析?大概是2008 年 8 月 9 日。
What about 2008-09-50? Some versions of PHP parse this as 20 October 2008.
怎么样2008-09-50?某些版本的 PHP 将此解析为20 October 2008。
So, if you are sure your input is in DD-MM-YYYYformat, it's better to use the solution offered by @Armin Ronacher.
因此,如果您确定您的输入DD-MM-YYYY格式正确,最好使用@Armin Ronacher提供的解决方案。
回答by Prof. Falken contract breached
This method works on bothWindows and Unix andis time-zoneaware, which is probably what you want if you work with dates.
这种方法适用于这两个Windows和Unix和是时区意识到,这可能是你想要什么,如果你一起工作的日期。
If you don't care about timezone, or want to use the time zone your server uses:
如果您不关心时区,或者想使用您的服务器使用的时区:
$d = DateTime::createFromFormat('d-m-Y H:i:s', '22-09-2008 00:00:00');
if ($d === false) {
die("Incorrect date string");
} else {
echo $d->getTimestamp();
}
1222093324(This will differ depending on your server time zone...)
1222093324 (这会因您的服务器时区而异...)
If you want to specify in which time zone, here EST. (Same as New York.)
如果要指定在哪个时区,这里是 EST。(与纽约相同。)
$d = DateTime::createFromFormat(
'd-m-Y H:i:s',
'22-09-2008 00:00:00',
new DateTimeZone('EST')
);
if ($d === false) {
die("Incorrect date string");
} else {
echo $d->getTimestamp();
}
1222093305
1222093305
Or if you want to use UTC. (Same as "GMT".)
$d = DateTime::createFromFormat(
'd-m-Y H:i:s',
'22-09-2008 00:00:00',
new DateTimeZone('UTC')
);
if ($d === false) {
die("Incorrect date string");
} else {
echo $d->getTimestamp();
}
1222093289
1222093289
Regardless, it's always a good starting point to be strict when parsing strings into structured data. It can save awkward debugging in the future. Therefore I recommend to always specify date format.
无论如何,在将字符串解析为结构化数据时严格执行始终是一个很好的起点。可以省去以后麻烦的调试。因此我建议始终指定日期格式。
回答by Till
回答by klit67
Using strtotime() function you can easily convert date to timestamp
使用 strtotime() 函数,您可以轻松地将日期转换为时间戳
<?php
// set default timezone
date_default_timezone_set('America/Los_Angeles');
//define date and time
$date = date("d M Y H:i:s");
// output
echo strtotime($date);
?>
More info: http://php.net/manual/en/function.strtotime.php
更多信息:http: //php.net/manual/en/function.strtotime.php
Online conversion tool: http://freeonlinetools24.com/
在线转换工具:http: //freeonlinetools24.com/
回答by Victor Bojica
Here is a very simple and effective solution using the splitand mtimefunctions:
这是一个使用split和mtime函数的非常简单有效的解决方案:
$date="30/07/2010 13:24"; //Date example
list($day, $month, $year, $hour, $minute) = split('[/ :]', $date);
//The variables should be arranged according to your date format and so the separators
$timestamp = mktime($hour, $minute, 0, $month, $day, $year);
echo date("r", $timestamp);
It worked like a charm for me.
它对我来说就像一种魅力。
回答by Ja?ck
If you want to know for sure whether a date gets parsed into something you expect, you can use DateTime::createFromFormat():
如果您想确定某个日期是否被解析为您期望的内容,您可以使用DateTime::createFromFormat():
$d = DateTime::createFromFormat('d-m-Y', '22-09-2008');
if ($d === false) {
die("Woah, that date doesn't look right!");
}
echo $d->format('Y-m-d'), PHP_EOL;
// prints 2008-09-22
It's obvious in this case, but e.g. 03-04-2008could be 3rd of April or 4th of March depending on where you come from :)
在这种情况下很明显,但例如03-04-2008可能是 4 月 3 日或 3 月 4 日,具体取决于您来自哪里:)
回答by Victor
Given that the function strptime()does not work for Windows and strtotime()can return unexpected results, I recommend using date_parse_from_format():
鉴于该函数strptime()不适用于 Windows 并且strtotime()可能返回意外结果,我建议使用date_parse_from_format():
$date = date_parse_from_format('d-m-Y', '22-09-2008');
$timestamp = mktime(0, 0, 0, $date['month'], $date['day'], $date['year']);

