如何在 PHP 中将日期转换为时间戳? [英] How to convert date to timestamp in PHP?

查看:45
本文介绍了如何在 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


或者如果您想使用 UTC.(与GMT"相同.)

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屋!

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