【发布时间】:2010-12-12 13:11:28
【问题描述】:
我有时间:
$today = time();
$date = date('h:i:s A', strtotime($today));
如果当前时间是“上午 1:00:00”,我如何再增加 10 个小时变成上午 11:00:00??
【问题讨论】:
我有时间:
$today = time();
$date = date('h:i:s A', strtotime($today));
如果当前时间是“上午 1:00:00”,我如何再增加 10 个小时变成上午 11:00:00??
【问题讨论】:
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
【讨论】:
+ 10 hours 添加到 strtotime 更优雅的解决方案 :)
time() 已经返回了一个以秒为单位的时间值。不完全确定您为什么将time() 传递给strtotime() - 如果您只是使用当前时间,只需使用time() w/o strtotime()。我假设(因为我只看了 OP)你在 $today 中有一个实际的字符串时间。
DateTime。其他一切最终都会给你带来麻烦。
$tz = new DateTimeZone('Europe/London');
$date = new DateTime($today, $tz);
$date->modify('+10 hours');
// use $date->format() to outputs the result.
见DateTime Class (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 的时间,您可以在第一个参数中使用Relative format。
在您的情况下,将 当前时间 增加 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');
除非指定时区,否则在所有情况下都将使用默认时区。
【讨论】: