Search code examples
phpdatetimephp-carbon

getting only time timestamp from string


Suppose I have a time string '9:30' which I want to convert to timestamp. What I do right now is extracting it and manually calculate the timestamp.

list($hour, $minute) = explode(':', '9:30');
$timestamp = $hour * 3600 + $minute * 60;

I'm wondering whether there is a smart way using Carbon or DateTime object.


Solution

  • I don't think you'll be able to get a timestamp from only hour or minute, as timestamp is number of seconds from 00:00:00 Thursday 1 January 1970 (check wikipedia link for more details). So without the date part you can't have a timestamp. Could you please explain how you're planning to use this?

    If you're planning to calculate a different timestamp from a given datetime, then you can just do it differently. Say you're planning to get the timestamp 1 day or 24 hours after given time, then you can do it like this (non object oriented way):

    $givenTimestamp = strtotime('17-06-2018 09:30:00');
    $dayInSeconds = 24*60*60;
    $calculatedTimeStamp = $givenTimestamp + $dayInSeconds;
    

    If you're just trying to get how many seconds has been passed for the time section of the timestamp (like 9:30 in your example for a given day), then you can just do it like this:

    list($hour, $minute) = explode(':', date ('H:i', strtotime('2018-06-16 09:30:00')));
    $secondsSinceStartOfDay = intval($hour)*60*60 + intval($minute) * 60;
    

    You may get the same result without using the intval on $hour and $minute, but it would be better to use intval on them to avoid possible issues in some cases.

    Update with Carbon

    From Carbon documentation, it seems like you still need the date part to generate the timestamp. So if you have your $date like this '2018-06-16' and $time like this '09:30', then you can recreate your datetime like this:

    $dateTimeString = $date .' '. $time .':00';
    $carbonDateTime = Carbon::parse($dateTimeString);
    // $carbonDateTime will now have your date time reference
    // you can now get the timestamp like this
    echo $carbonDateTime->timestamp;