向时间变量添加 1 小时


Adding 1 hour to time variable

我有一个时间,我想添加一个小时:

$time = '10:09';

我试过:

$time = strtotime('+1 hour');
strtotime('+1 hour', $time);
$time = date('H:i', strtotime('+1 hour'));

但以上都不起作用。

我工作。

$timestamp = strtotime('10:09') + 60*60;
$time = date('H:i', $timestamp);
echo $time;//11:09

解释:

strtotime('10:09')创建一个以秒为单位的数字时间戳,类似于 1510450372 .只需添加或删除所需的秒数,并使用date()将其转换回人类可读的格式。

$timestamp = strtotime('10:09') + 60*60; // 10:09 + 1 hour
$timestamp = strtotime('10:09') + 60*60*2; // 10:09 + 2 hours
$timestamp = strtotime('10:09') - 60*60; // 10:09 - 1 hour

time()还创建了一个数字时间戳,但现在。您可以以相同的方式使用它。

$timestamp = time() + 60*60; // now + 1 hour

你可以这样做

    echo date('Y-m-d H:i:s', strtotime('4 minute'));
    echo date('Y-m-d H:i:s', strtotime('6 hour'));
    echo date('Y-m-d H:i:s', strtotime('2 day'));
$time = '10:09';
$timestamp = strtotime($time);
$timestamp_one_hour_later = $timestamp + 3600; // 3600 sec. = 1 hour
// Formats the timestamp to HH:MM => outputs 11:09.
echo strftime('%H:%M', $timestamp_one_hour_later);
// As crolpa suggested, you can also do
// echo date('H:i', $timestamp_one_hour_later);

有关详细信息,请查看 PHP 手册中的 strtotime((、strftime(( 和 date((。

顺便说一句,在你的初始代码中,你需要添加一些引号,否则你会得到PHP语法错误:

$time = 10:09; // wrong syntax
$time = '10:09'; // syntax OK
$time = date(H:i, strtotime('+1 hour')); // wrong syntax
$time = date('H:i', strtotime('+1 hour')); // syntax OK

试试这个它对我有用。

$time="10:09";
$time = date('H:i', strtotime($time.'+1 hour'));
echo $time;

2020 年更新

奇怪的是,没有人建议OOP方式:

$date = new 'DateTime(); //now
$date->add(new 'DateInterval('PT3600S'));//add 3600s / 1 hour

$date = new 'DateTime(); //now
$date->add(new 'DateInterval('PT60M'));//add 60 min / 1 hour

$date = new 'DateTime(); //now
$date->add(new 'DateInterval('PT1H'));//add 1 hour

以字符串格式提取它:

var_dump($date->format('Y-m-d H:i:s'));

您可以尝试以下代码:

$time = '10:09';
echo date( 'H:i', strtotime( '+1 hour' , strtotime($time) ) );

简单而智能的解决方案:

date("H:i:s", time()+3600);

您可以使用:

$time = strtotime("10:09") + 3600;
echo date('H:i', $time);

date_add:http://www.php.net/manual/en/datetime.add.php

我工作使用 DateTime::modifydate_modify : https://www.php.net/manual/en/datetime.modify.php

// Example:
$timestamp = 1680947903;
// Timestamp to datetime
$date = new 'DateTime('@'. $timestamp );
$date->modify('+1 hour');

结果

我遇到了类似的问题,解决方法是说"小时"而不是"小时"。

小心添加 3600!! 可能是日期更改的问题,因为 UNIX 时间戳格式在天之前使用飞蛾。

例如 2012-03-02 23:33:33

将变为 2014-01-13 13:00:00 通过添加 3600 更好地使用 MKtime 和日期函数,他们可以处理这个问题以及添加 25 小时等事情。

> 2021 年更新

为我工作..

$text = str_replace(':PM', '', '19:00:PM');   //19:00:PM  //Removes :PM
$text = str_replace(':AM', '', $text);   //Removes :AM
$time = strtotime($text);   //19:00
$startTime = date("H:i:A", strtotime('- 1 hours', $time));
$endTime = date("H:i:A", strtotime('+ 1 hours', $time));

输出:

echo $startTime; //18:00:PM
echo $endTime;  //20:00:PM