webignition/readable-duration

将秒数转换为人类可读的便捷时长

2.1 2019-04-17 14:57 UTC

This package is auto-updated.

Last update: 2024-09-18 02:27:03 UTC


README

你是否曾想过,秒数可能对应多长时间,用人类大脑更易理解的单位来表示?

现在你可以将秒数转换为人类可读的便捷时长了!

特性

  • 获取给定值对应的年、月、日、时、分和秒
  • 以年、月、日、时、分或秒为单位获取秒数
  • 获取最合适的人类可读值

获取给定值对应的年、月、日、时、分和秒

<?php
use webignition\ReadableDuration\Factory;

/**
 * 100000 seconds is 1 day, 3 hours, 46 minutes and 40 seconds
 */
$factory = new Factory();    
$readableDuration = $factory->create(100000);

$readableDuration->getDays();
// 1

$readableDuration->getHours();
// 3

$readableDuration->getMinutes();
// 46

$readableDuration->getSeconds();
// 40

以年、月、日、时、分或秒为单位获取秒数

<?php

use webignition\ReadableDuration\Factory;

/**
 * 100000 seconds as years, months, days, hours, minute or seconds
 *
 * Note: these are human-readable convenience representations not exact
 *
 * 100000 seconds is strictly 1.16 days. As far as convenience is concerned, that's 1 day.
 * 100000 seconds is strictly 27.78 hours. As far as convenience is concerned, that's 28 hours.
 */
$factory = new Factory();    
$readableDuration = $factory->create(100000);

$readableDuration->getInYears();
// 0

$readableDuration->getInMonths();
// 0

$readableDuration->getInDays();
// 1

$readableDuration->getInHours();
// 28

$readableDuration->getInMinutes();
// 1667

$readableDuration->getInSeconds();
// 100000

获取最合适的人类可读值

<?php

use webignition\ReadableDuration\Factory;

/**
 * 100000 seconds:
 *
 * - represented as a single time unit is 1 day
 * - represented as two time units is 1 day 4 hours
 * - represented as three time units is 1 day 3 hours 47 minutes
 *
 */
$factory = new Factory();    
$readableDuration = $factory->create(100000);

/**
 * 100000 seconds, as a single time unit is 1 day
 */
$this->factory->getInMostAppropriateUnits($readableDuration);
// [
//     [
//         'unit' => 'day',
//         'value' => 1
//     ]
// ]


/**
 * 100000 seconds, as two time units is 1 day 4 hours
 */
$this->factory->getInMostAppropriateUnits($readableDuration, 2);
// [
//     [
//         'unit' => 'day',
//         'value' => 1
//     ],
//     [
//         'unit' => 'hour',
//         'value' => 4
//     ]
// ]

/**
 * 100000 seconds, as three time units is 1 day 3 hours 47 minutes
 */
$this->factory->getInMostAppropriateUnits($readableDuration, 3);
// [
//     [
//         'unit' => 'day',
//         'value' => 1
//     ],
//     [
//         'unit' => 'hour',
//         'value' => 3
//     ],
//     [
//         'unit' => 'minute',
//         'value' => 47
//     ]
// ]