如何在 PHP 中将日期转换为时间戳? [英] How to convert date to timestamp in PHP?
问题描述
我如何从例如获取时间戳22-09-2008
?
How do I get timestamp from e.g. 22-09-2008
?
推荐答案
此方法适用于 Windows 和 Unix 和时区,这可能是您想要的处理日期.
This method works on both Windows and Unix and is time-zone aware, which is probably what you want if you work with dates.
如果您不关心时区,或者想使用您的服务器使用的时区:
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 (这会因您的服务器时区而异...)
如果你想指定在哪个时区,这里是 EST.(与纽约相同.)
If you want to specify in which time zone, here EST. (Same as New York.)
$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
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
无论如何,在将字符串解析为结构化数据时,严格始终是一个好的起点.可以省去日后麻烦的调试.因此我建议始终指定日期格式.
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.
这篇关于如何在 PHP 中将日期转换为时间戳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!