Summer sale! Save 50% on access to our entire library of courses.Join here →

Only Show Hours and Minutes using Carbon toTimeString

June 19th, 2024

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.

Thanks for reading! If you found this article helpful, you might enjoy our practical screencasts too.
Alex Garrett-Smith
Share :


No comments, yet. Be the first to leave a comment.

Tagged under