在字符串表示中添加军事时间

发布于 2024-09-12 13:33:22 字数 138 浏览 1 评论 0原文

所以我想做的是以军事时间的形式将两个字符串加在一起。这是一个例子。

时间1 = "01:00"; 时间2 =“04:30”;

将两者相加将得到“05:30”。这看起来非常简单,但对于新学习者来说这是漫长的一天。任何帮助将不胜感激。

So what I am trying to do is add two strings together in the form of military time. Here is the example.

Time1 = "01:00";
Time2 = "04:30";

Adding the two together would produce "05:30". This seems incredibly simple, but it has been a long long day for a new learner. Any help would be greatly appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心的位置 2024-09-19 13:33:22

您可以在 PHP 5.3 中执行类似的操作:

$d = new DateTime("01:00");
$f = $d->add(new DateInterval("PT04H30M"));
echo $f->format("H:i"); //outputs 05:30

将 04:30 转换为 PT04H30M 应该很简单。请注意,这是否确实是您想要的取决于您所说的“04:30”的含义。此代码可能会也可能不会将 4*60+30 分钟加起来为实际时间。

如果您的意思是“时钟上有 4 小时 30 分钟”,那么这始终是正确的。但是,如果您的意思是“4*60+30 分钟”,则取决于日期和时区。示例:

$d = new DateTime("2010-03-28 01:00 Europe/Lisbon");
$f = $d->setTimestamp($d->getTimestamp() + (4*60+30)*60);
echo $f->format("H:i"); //outputs 06:30 due to DST

PHP 5.2 的 last 情况(假设当前日期和默认时区)的替代实现是 对于

echo date("H:i", strtotime("+4 hours +30 mins", strtotime("01:00")));

第一种情况,我们必须执行以下操作:

date_default_timezone_set("UTC");
echo date("H:i", strtotime("+4 hours +30 mins", strtotime("01:00")));

You can do something like this in PHP 5.3:

$d = new DateTime("01:00");
$f = $d->add(new DateInterval("PT04H30M"));
echo $f->format("H:i"); //outputs 05:30

Converting 04:30 to PT04H30M should be trivial. Note that whether this is actually what you want depends on what you mean by "04:30". This code may or may not sum 4*60+30 minutes to the actual time.

If you mean "4 hours and 30 minutes on the clock" this is always correct. However, if you mean "4*60+30 minutes", it depends on the day and timezone. Example:

$d = new DateTime("2010-03-28 01:00 Europe/Lisbon");
$f = $d->setTimestamp($d->getTimestamp() + (4*60+30)*60);
echo $f->format("H:i"); //outputs 06:30 due to DST

An alternate implementation of the last case (assuming current day and default timezone) for PHP 5.2 is

echo date("H:i", strtotime("+4 hours +30 mins", strtotime("01:00")));

For the first case, we must do:

date_default_timezone_set("UTC");
echo date("H:i", strtotime("+4 hours +30 mins", strtotime("01:00")));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文