reply/microtime

2.0.2 2021-09-14 08:56 UTC

This package is auto-updated.

Last update: 2024-09-14 15:18:24 UTC


README

Microtime 是一个用纯 PHP 编写的库,提供了一个接口和类来处理微秒。PHP 提供了通过 microtime() 函数获取当前时间戳(秒和微秒)的可能性,但得到的两个值必须始终进行转换,以获得自 Unix 纪元以来的微秒数。Microtime 类为您完成这项工作。这允许您从不同的格式创建 Microtime 对象,并将其转换为不同的格式,如 DateTime 对象、整数和字符串。

需求

Microtime 需要以下内容

  • PHP 7.1 或更高版本

安装

Microtime 通过 Composer 安装。要在您的项目中添加 Microtime 依赖项,可以

运行以下命令以使用最新稳定版本

    composer require reply/microtime

或者如果您想使用最新的 master 版本

    composer require reply/microtime:dev-master

当然,您也可以手动编辑 composer.json 文件

{
    "require": {
       "reply/microtime": "^2.0"
    }
}

入门

以下是一个 Microtime 库的基本使用示例

<?php

use Reply\Microtime\Microtime;

// Creates a Microtime object from current timestamp
$microtime = Microtime::fromNow();

// Creates a Microtime object from a string containing seconds and microseconds
$microtime = Microtime::fromString('0.34497500 1589445224');
// or
$microtime = Microtime::fromMicrotime('0.34497500 1589445224');

// Creates a new Microtime object from an integer containing the microseconds since the unix epoch
$microtime = Microtime::fromInt(1589445224344975);
// or
$microtime = Microtime::fromMicroseconds(1589445224344975);

// Creates a new Microtime object from a float containing the result of the microtime(true) function
$microtime = Microtime::fromFloat(1589445622.7431);

// Creates a new Microtime object from an integer containing the seconds since the unix epoch
$microtime = Microtime::fromSeconds(1589445622);

// Creates a new Microtime object from a DateTime object
$microtime = Microtime::fromDateTime(new \DateTime());

// Returns the microtime as string
$string = $microtime->toString();
// or
$string = (string) $microtime;
// or
$string = "Time in microseconds: $microtime";

// Returns the microtime as integer
$int = $microtime->toInt();

// Returns the microtime as float
$float = $microtime->toFloat();

// Returns the microtime as string in the format of the microtime() function
$string = $microtime->toMicrotime();

// Returns the microtime in a DateTime object
$dateTime = $microtime->toDateTime();

// Returns the microtime in a DateTimeImmutable object
$dateTimeImmutable = $microtime->toDateTimeImmutable();

贡献

欢迎您为 Microtime 做贡献。以下是一些您可以做的事情来做出贡献。