如何在 php 中获取时间差的分钟数
在本文中,我们将介绍在 php 中获取分钟时差的方法。
-
使用
date_diff()
函数 - 使用数学公式
在 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.
转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处
本文地址:
相关文章
发布时间:2023/03/29 浏览次数:156 分类:php
-
本教程演示了如何将用户从页面重定向到 php 中的其他页面
发布时间:2023/03/29 浏览次数:128 分类:php
-
本文介绍如何在 php 中使用三元运算符作为 if else 的简写