Search code examples
phplaravelphp-carbon

Carbon timestamp property returns wrong date millis


I'm trying to return a date parsed to the current server timezone (is stored in UTC) based on the day, the month and the year only. For that reason I have a function that looks like this:

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

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

The problem is that always the 'date' key in the array gets 1577113131 for example (and consecutive numbers each time I execute the method), so:

  • First execution: 1577113515
  • Second execution: 1577113525
  • Third execution: 1577113548
  • And so on...

Although the timestamp represents the right date in Y-m-d, the variation each time I execute the method shouldn't happen.

So, how can I solve this problem and get the timestamp in the millisecond? I have printed what's in the 'date' Carbon object and it seems to have the right date information:

^ 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)
}

The expected output is:

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

Taking into account the date: 2019-12-23 10:08:54.0 America/Bogota (-05:00)


Solution

  • Lets try this, it should work for you

    $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;
    

    And you can change your example like this:

    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,
        ];
    }