编程

PHP 8.4: Date: 新增 DateTime(Immutable)::get/setMicroseconds 方法

184 2024-04-03 20:46:00

PHP 8.4 及其此后的版本中, DateTimeDateTimeImmutable 类支持通过 getMicrosecondssetMicroseconds 方法获取和设置 DateTime/DateTimeImmutable 对象的秒数。

虽然可以使用时间戳创建/更新 DateTimeDateTimeImmutable 对象,但新方法允许设置微秒小数,而无需知道或修改小时、分钟、秒或日期和时间的其余部分。

DateTimeDateTimeImmutable 类允许将微秒值作为最后一个参数(int $microsecond)进行设置。时间戳的微秒小数可以通过 u 格式,并且将该字符串值强制为整数。

新增 getMicrosecondssetMicroseconds 方法

新增的 getMicrosecondssetMicroseconds 方法都可以在 DateTimeDateTimeImmutable 类中使用:

class DateTime {
    // ...
    public function getMicroseconds(): int {}

    public function setMicroseconds(int $microseconds): static {}
    // ...
}

在现有的 DateTimeDateTimeImmutable 对象上,getMicroseconds 方法以整型的方式返回时间抽的毫秒部分:

// 2024-02-06 08:40:46.899561 UTC (+00:00)
$date = new DateTimeImmutable(); 

$date->getMicroseconds(); // (int) 899561

类似地,setTimestamp 方法接收整型值以设置时间戳的毫秒部分:

// 2024-02-06 08:40:46.899561 UTC (+00:00)
$date = new DateTime(); 

$date->setMicroseconds(426286);
$date->getMicroseconds(); // (int) 426286

setMicroseconds 接受的值

DateTime::setMicrosecondsDateTimeImmutable::setMicroseconds 方法接受整型值范围为 >= 0<= 999999。这确保了设置微秒小数不会修改时间戳的秒部分。

传递超出此范围的值会导致 DateRangeError 异常。

$date = new DateTimeImmutable();
$date->setMicroseconds(1000000);
DateRangeError: DateTimeImmutable::setMicroseconds(): Argument #1 ($microseconds) must be between 0 and 999999, 1000000 given.

现有设置/获取微秒的方式

新增的 setMicrosecondsgetMicroseconds 方法不是从 DateTimeDateTimeImmutable 对象中获取微秒的唯一方式。

最简单的方式是 setTime 方法,它接受微秒值作为参数:

$date = new DateTimeImmutable();
$date = $date->setTime(hour: 10, minute: 44, second: 0, microsecond: 628115);
$date->format('u'); // string(6) "628115"

该方法的缺点是必须知道小时、分钟和秒值。以下代码从现有的值中显示重用现有日期、小时、分钟和秒值设置微秒值:

$date = new DateTimeImmutable();
$date = $date->setTime(
    hour: (int) $date->format('G'),
    minute: (int) $date->format('i'),
    second: (int) $date->format('s'),
    microsecond: 628115
);

(int) $date->format('u'); // int "628115"

新的 setMicrosecondsgetMicroseconds 方法使其在所需设置/获取微秒值时变得直观。

向后兼容性影响

除非用户空间 PHP 类扩展了 DateTimeDateTimeImmutable 类,并使用非兼容签名声明了同一个方法,该方法不会导致现有代码出现任何兼容性问题。