Carbon timestamp 属性 returns 错误日期 millis

Carbon timestamp property returns wrong date millis

我正在尝试 return 仅根据日、月和年将日期解析为当前服务器时区(以 UTC 格式存储)。出于这个原因,我有一个看起来像这样的函数:

private function getFormattedDate(string $stringDate): array
{
    $date = Carbon::createFromFormat(
        'Y-m-d',
        $stringDate,
        config('app.timezone')
    );

    return [
        'date' => $date->timestamp,
        'timezone' => $date->timezoneName,
    ];
}

问题是数组中的 'date' 键总是得到 1577113131(每次执行该方法时都是连续的数字),所以:

虽然时间戳代表 Y-m-d 中的正确日期,但每次执行该方法时都不应该发生变化。

那么,如何解决这个问题并获取毫秒级的时间戳呢?我打印了 'date' Carbon 对象中的内容,它似乎具有正确的日期信息:

^ Carbon\Carbon @1577113734 {#1048
#constructedObjectId: "00000000212d5614000000005c7c5f51"
#localMonthsOverflow: null
#localYearsOverflow: null
#localStrictModeEnabled: null
#localHumanDiffOptions: null
#localToStringFormat: null
#localSerializer: null
#localMacros: null
#localGenericMacros: null
#localFormatFunction: null
#localTranslator: null
#dumpProperties: array:3 []
#dumpLocale: null
date: 2019-12-23 10:08:54.0 America/Bogota (-05:00)
}

预期输出为:

'date' => 1577113734000,
'timezone' => 'America/Bogota'

考虑到日期:2019-12-23 10:08:54.0 America/Bogota (-05:00)

让我们试试这个,它应该适合你

$format = 'Y-m-d';
$date = Carbon::createFromFormat($format, '2009-02-15');
$nowInMilliseconds = (int) ($date->timestamp . str_pad($date->milli, 3, '0', STR_PAD_LEFT));
echo $nowInMilliseconds;

你可以这样改变你的例子:

private function getFormattedDate(string $stringDate): array
{
    $date = Carbon::createFromFormat(
        'Y-m-d',
        $stringDate,
        config('app.timezone')
    );

    $dateInMilliseconds = (int) ($date->timestamp . str_pad($date->milli, 3, '0', STR_PAD_LEFT));

    return [
        'date' => $dateInMilliseconds,
        'timezone' => $date->timezoneName,
    ];
}

使用!:

$date = Carbon::createFromFormat(
    '!Y-m-d',
    $stringDate,
    config('app.timezone')
);

https://www.php.net/manual/en/datetime.createfromformat.php

createFromFormat是原生的PHP函数,默认取当前时间(未指定单位的当前值),如果使用!前缀,则取每个的最小值(因此 hours/minutes/seconds 为 0)。