PHP - 将时间加到当前时间,最佳实践

标签 php datetime time sum

您好,我正在尝试将时间与当前日期时间相加,这段代码似乎有效:

$now = time();
$_day = strtotime('+1day',$now);
$_week = strtotime('+7day',$now);
$_month = strtotime('+1month',$now);
$_year = strtotime('+1year',$now);

我想知道是否有任何其他方法,也许是更好的方法.. 谁能告诉我新的方法以及我应该转向另一种语法的原因? 我想尽可能准确地做到这一点,所以如果我能反射(reflect)这个脚本那就太好了!

谢谢

编辑:

需要说明的是,我需要使用 unix 时间戳,我不需要格式化日期/日期时间

最佳答案

如果您使用的 PHP 版本允许 (PHP 5 >= 5.3.0) 您可以使用 DateTimeDateInterval类,您可以使用它们。

例子:

$dateTime=new DateTime();
$plusDay=new DateInterval('P1D');
var_dump($dateTime->add($plusDay));

$dateTime=new DateTime();
$plusWeek=new DateInterval('P1W');
var_dump($dateTime->add($plusWeek));

$dateTime=new DateTime();
$plusMonth=new DateInterval('P1M');
var_dump($dateTime->add($plusMonth));

希望对您有所帮助。

关于PHP - 将时间加到当前时间,最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14030468/

相关文章:

php - 在 Controller 中应用函数后, View 不显示相同的内容

Phpmailer 和异步发送电子邮件

php - 在包含 HTML 代码的字符串中抓取 URL

python - 时间不准确或代码效率低下?

javascript - 时间日期对象 JavaScript getUTCMilliseconds

PHP获取本地日期和时间

Android:将字符串转换为时间

php - 如何限制/偏移每个唯一 ID 返回多行的查询?

php - 将德语日期字符串转换为日期并检查是否在今天之前

python - 在 pandas 中滚动平均值后重新采样