meklis/php-duration

在冒号格式的时间、可读时间与秒之间进行转换

1.2.0 2022-01-23 20:42 UTC

This package is auto-updated.

Last update: 2024-09-24 03:24:56 UTC


README

在冒号格式的时间、可读时间与秒之间进行时长转换

Total Downloads License Minimum PHP Version PayPal

Current Release Build Status Coverage Status

此包的创建有一个非常具体的目标,即为用户提供一种简单的方法,将某件事情花费的时间作为时长输入。

库可以接受冒号分隔的格式,例如 2:43 代表 2 分钟 43 秒,也可以写成可读或缩写的格式,例如 6m21s 代表 6 分钟 21 秒。

两者都可以转换为秒和分钟,以便于精确存储到数据库中。

秒、冒号分隔、缩写,三者都可以解析和互换。

  • 支持小时、分钟和秒(包括微秒)
  • 可读输入支持“小时”、“分钟”、“秒”等单词的任何形式
    • 例如,您可以输入 1h4m2s 或 4 Hr. 32 Min.

安装

composer require khill/php-duration:~1.0

用法

use Khill\Duration\Duration;


$duration = new Duration('7:31');

echo $duration->humanize();  // 7m 31s
echo $duration->formatted(); // 7:31
echo $duration->toSeconds(); // 451
echo $duration->toMinutes(); // 7.5166
echo $duration->toMinutes(null, 0); // 8
echo $duration->toMinutes(null, 2); // 7.52
$duration = new Duration('1h 2m 5s');

echo $duration->humanize();  // 1h 2m 5s
echo $duration->formatted(); // 1:02:05
echo $duration->toSeconds(); // 3725
echo $duration->toMinutes(); // 62.0833
echo $duration->toMinutes(null, 0); // 62
// Configured for 6 hours per day
$duration = new Duration('1.5d 1.5h 2m 5s', 6);

echo $duration->humanize();  // 1d 4h 32m 5s
echo $duration->formatted(); // 10:32:05
echo $duration->toSeconds(); // 37925
echo $duration->toMinutes(); // 632.083333333
echo $duration->toMinutes(null, 0); // 632
$duration = new Duration('4293');

echo $duration->humanize();  // 1h 11m 33s
echo $duration->formatted(); // 1:11:33
echo $duration->toSeconds(); // 4293
echo $duration->toMinutes(); // 71.55
echo $duration->toMinutes(null, 0); // 72

注意

您无需为每次转换创建一个新对象,也可以将三种格式中的任何一种传递给任何方法以获取即时输出。

$duration = new Duration;

echo $duration->humanize('1h 2m 5s');  // 1h 2m 5s
echo $duration->formatted('1h 2m 5s'); // 1:02:05
echo $duration->toSeconds('1h 2m 5s'); // 3725
echo $duration->toMinutes('1h 2m 5s'); // 62.0833
echo $duration->toMinutes('1h 2m 5s', true); // 62