Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to represent time without date in PHP

Tags:

php

I'd like to represent time (standalone) in PHP without the date part. I've tried using strtotime and DateTime::createFromFormat but both add a date part to it. Laravel's carbon library descends from DateTime and also doesn't cater for this.

My use case is that of representing bus depart and arriving times from a station. The buses depart everyday at the same time so I don't want/need the date part of it.

Python has datetime.time and Java has java.time.LocalTime, is there a direct equivalent of this in PHP? Should I create a custom class for it?

Cheers

like image 236
Paulo Phagula Avatar asked Feb 06 '18 08:02

Paulo Phagula


Video Answer


2 Answers

  1. Create DateTime object and format this object to show only time:

    $date = new \DateTime("now");
    echo $date->format("H:i:s");
    

    or do the same thing in one line:

    echo (new \DateTime("now"))->format("H:i:s");
    
  2. Use date function:

    echo date("H:i:s");
    
like image 194
Krzysztof Raciniewski Avatar answered Oct 06 '22 23:10

Krzysztof Raciniewski


PHP doesn't have a direct equivalent to either Python datetime.time nor Java java.time.LocalTime. A Time value-object should be created for this case in a per-need basis.

like image 26
Paulo Phagula Avatar answered Oct 07 '22 01:10

Paulo Phagula