如何在 PHP 中获取时间差的分钟数

[在 PHP 中使用 date_diff() 函数来获取分钟的时间差]

我们将使用内置函数 date_diff() 来获得以分钟为单位的时间差。

为此,我们需要一个开始日期和结束日期。我们将使用 date_diff() 函数来计算它们的时间差,单位是分钟。使用这个函数的正确语法如下。

date_diff($DateTimeObject1, $DateTimeObject2);

内置函数 date_diff() 有两个参数。其详细参数如下

参数说明
$DateTimeObject1强制它是一个 DateTime 对象。它代表开始日期。
$DateTimeObject2强制它也是一个 DateTime 对象,它代表结束日期。

这个函数在成功时返回开始日期和结束日期之间的差值,失败时返回 FALSE。如果失败,则返回 FALSE。

下面的程序显示了我们如何使用 date_diff() 函数来获得以分钟为单位的时间差。

<?php 
$dateTimeObject1 = date_create('2019-06-16'); 
$dateTimeObject2 = date_create('2020-06-16'); 
  
$difference = date_diff($dateTimeObject1, $dateTimeObject2); 
echo ("The difference in days is:");
echo $difference->format('%R%a days');
echo "\n";
$minutes = $difference->days * 24 * 60;
$minutes += $difference->h * 60;
$minutes += $difference->i;
echo("The difference in minutes is:");
echo $minutes.' minutes';
?>

函数 date_diff() 返回了一个对象,表示两个日期之间的差异。

输出:

The difference in days is:+366 days
The difference in minutes is:527040 minutes

现在我们将找到时间差。

<?php 
$dateTimeObject1 = date_create('17:13:00'); 
$dateTimeObject2 = date_create('12:13:00'); 
  
$difference = date_diff($dateTimeObject1, $dateTimeObject2); 
echo ("The difference in hours is:");
echo $difference->h;
echo "\n";
$minutes = $difference->days * 24 * 60;
$minutes += $difference->h * 60;
$minutes += $difference->i;
echo("The difference in minutes is:");
echo $minutes.' minutes';
?>

输出:

The difference in hours is:5
The difference in minutes is:300 minutes

[在 PHP 中使用数学公式来获取时间差的分钟数

在 PHP 中,我们还可以使用不同的数学公式来获取分钟的时间差。获取分钟时差的程序如下。

<?php
$to_time = strtotime("10:42:00");
$from_time = strtotime("10:21:00");
$minutes = round(abs($to_time - $from_time) / 60,2);
echo("The difference in minutes is: $minutes minutes.");
?>

输出:

The difference in minutes is: 21 minutes

我们也可以用下面的方法求出分钟的时差。

<?php
$start = strtotime('12:01:00');
$end = strtotime('13:16:00');
$minutes = ($end - $start) / 60;
echo "The difference in minutes is $minutes minutes.";
?>

输出:

The difference in minutes is 75 minutes.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小柴没吃饱

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值