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

查看:89
本文介绍了如何在PHP中将日期转换为时间戳?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从例如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天全站免登陆