繁体   English   中英

php 中的时间计算(加 10 小时)?

[英]Time calculation in php (add 10 hours)?

我得到了时间:

$today = time();
$date = date('h:i:s A', strtotime($today));

如果当前时间是“1:00:00 am”,我如何再增加 10 个小时变成 11:00:00 am??

strtotime()返回一个数字,表示以秒为单位的时间。 要增加它,请添加您要添加​​的相应秒数。 10 小时 = 60*60*10 = 36000,所以...

$date = date('h:i:s A', strtotime($today)+36000); // $today is today date

编辑:我假设你在 $today 中有一个字符串时间 - 如果你只是使用当前时间,甚至更简单:

$date = date('h:i:s A', time()+36000); // time() returns a time in seconds already
$tz = new DateTimeZone('Europe/London');
$date = new DateTime($today, $tz);
$date->modify('+10 hours');
// use $date->format() to outputs the result.

请参阅DateTime 类(PHP 5 >= 5.2.0)

$date = date('h:i:s A', strtotime($today . ' + 10 hours'));

(未经测试)

您可以简单地使用DateTime类,OOP 样式。

<?php
$date = new DateTime('1:00:00');
$date->add(new DateInterval('PT10H'));
echo $date->format('H:i:s a'); //"prints" 11:00:00 a.m
$date = date('h:i:s A', strtotime($today . " +10 hours"));

现在显示的完整代码和 10 分钟添加.....

$nowtime = date("Y-m-d H:i:s");
echo $nowtime;
$date = date('Y-m-d H:i:s', strtotime($nowtime . ' + 10 minute'));
echo "<br>".$date;

为了使用strtotime增加或减少时间,您可以在第一个参数中使用相对格式

在您的情况下,将当前时间增加 10 小时:

$date = date('h:i:s A', strtotime('+10 hours'));

如果您需要将更改应用于另一个时间戳,则可以指定第二个参数。

笔记:

不建议将此函数用于数学运算。 在 PHP 5.3 及更高版本中最好使用DateTime::add()和 DateTime::sub(),或者在 PHP 5.2 中使用 DateTime::modify()。

所以,自 PHP 5.3 起推荐的方式

$dt = new DateTime(); // assuming we need to add to the current time
$dt->add(new DateInterval('PT10H'));
$date = $dt->format('h:i:s A');

或使用别名:

$dt = date_create(); // assuming we need to add to the current time
date_add($dt, date_interval_create_from_date_string('10 hours')); 
$date = date_format($dt, 'h:i:s A');

在所有情况下,除非指定时区,否则将使用默认时区。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM