gpt4 book ai didi

php - 在 PHP 中添加时间间隔的最佳方法是什么?

转载 作者:可可西里 更新时间:2023-10-31 22:19:35 25 4
gpt4 key购买 nike

我想将时间添加到现有日期。我有 2 个字符串变量:

$date     = "2013-01-05 10:55:15";
$interval = "50:25:10";

我想计算最终日期“2013-01-07 13:20:25”。小时数可以大于 23,这意味着该间隔可以大于一整天。

执行此操作的最佳方法是什么?

最佳答案

使用DateTime API :

$date = new DateTime("2013-01-05 10:55:15");
$date->add(new DateInterval("PT50H25M10S"));

然后您可以将其转换回字符串,其日期格式与您在 date() 函数中使用的日期格式相同,如果您希望:

$string = $date->format("Y-m-d H:i:s");

有关 DateInterval 定义的更多信息,请访问此页面:

DateInterval

The format starts with the letter P, for "period." Each duration period is represented by an integer value followed by a period designator. If the duration contains time elements, that portion of the specification is preceded by the letter T.

Here are some simple examples. Two days is P2D. Two seconds is PT2S. Six years and five minutes is P6YT5M.

所以在这种情况下 PT50H25M10S 表示 50 小时 25 分 10 秒

请注意,DateInterval 仅在 PHP 5.3 之后可用,如果您必须使用较低版本,您可以使用如下内容:

 $time = strtotime("2013-01-05 10:55:15");
$time += 55*60*60 + 25*60 + 10;
$newDate = date("Y-m-d H:i:s");

关于php - 在 PHP 中添加时间间隔的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19036492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com