magroski/time-buddy

处理时间和日期区间的库

v1.0.2 2022-11-28 19:39 UTC

This package is auto-updated.

Last update: 2024-09-28 23:22:14 UTC


README

Latest Stable Version Minimum PHP Version CircleCI GitHub license

此库为时间和日期操作提供了一些语法糖,包括无需在环境中添加多个地区即可动态进行格式本地化。

地区设置在 src/Provider 文件夹中。欢迎提交 pull-requests。

使用示例

创建

# Default
$time = new Time();

# From unix timestamp
$time = Time::createFromUnixTstamp(time());

# From DateTime
$dateTime = new \DateTime();
$time = Time::createFromDateTime($dateTime);

# From DateTimeImmutable
$immutable = new \DateTimeImmutable();
$time = new Time($immutable);

操作(时间不可变,因此操作将生成新的对象)

$firstTime = new Time();

$secondTime = $firstTime->add(100);

$thirdTime = $firstTime->subtract(100);

格式化

$time = new Time();
$time->format('d F Y'); # 20 May 2019

$time->setLocale('pt_BR');
$time->format('d F Y'); # 20 Maio 2019

生成日期区间

$time = new Time();
$laterTime = new Time();

# From Time
$interval = $time->diff($laterTime);

# Staticaly
$interval = DateInterval::createFromTime($time, $laterTime);

# Staticaly from a single time
$interval = DateInterval::createFromTime($time); # Second argument is current time