Only Show Hours and Minutes using Carbon toTimeString

June 19th, 2024 • 1 minute read time

The toTimeString method in Carbon allows you to set a precision. Let's look at the options.

If you're outputting a date/time, chances are you don't need to display the seconds. By default, using toTimeString outputs hours, minutes and seconds.

$post->created_at->toTimeString(); // 10:51:37

The toTimeString method accepts a precision parameter. To display a time string from Carbon without the seconds, pass in minute as the precision:

$post->created_at->toTimeString('minute'); // 10:51

As you might have guessed, we can take this a step further and provide hour as the precision too, which would show only the hour.

$post->created_at->toTimeString('hour'); // 10

Easy as that. You're now able to control the output of toTimeString and only show hours and minutes.

If you found this article helpful, you'll love our practical screencasts.
Author
Alex Garrett-Smith
Share :

Comments

No comments, yet. Be the first!

Tagged under