DEV Community

Cover image for PHP Carbon Formatting that Readable for Humans
Code And Deploy
Code And Deploy

Posted on

PHP Carbon Formatting that Readable for Humans

Originally posted @ https://codeanddeploy.com visit and download the sample code:
https://codeanddeploy.com/blog/php/php-carbon-formatting-that-readable-for-humans

In this example, I will show you an example of how to use Carbon Formatting dates in PHP that are readable for humans.

See the example below:

PHP Carbon Format to Date Example

<?php

$date = Carbon::now();

echo $date->toDateString();
//Result: 2022-05-06
Enter fullscreen mode Exit fullscreen mode

PHP Carbon Format to Date & Time Example

<?php

$date = Carbon::now();

echo $date->toDateTimeString();
//Result: 2022-05-06 07:20:48
Enter fullscreen mode Exit fullscreen mode

PHP Carbon Formatted Example

<?php

$date = Carbon::now();

echo $date->toFormattedDateString();
//Result: May 6, 2022
Enter fullscreen mode Exit fullscreen mode

PHP Carbon Format to Time Example

<?php

$date = Carbon::now();

echo $date->toTimeString();
//Result: 07:24:08
Enter fullscreen mode Exit fullscreen mode

PHP Carbon Format to Day, Date, and Time

<?php

$date = Carbon::now();

echo $date->toDayDateTimeString();
//Result: Fri, May 6, 2022 7:25 AM
Enter fullscreen mode Exit fullscreen mode

PHP Carbon Format Days Ago

<?php

echo Carbon::now()->subDays(3)->diffForHumans();
//Result: 3 days ago
Enter fullscreen mode Exit fullscreen mode

PHP Carbon Format Weeks Ago

<?php

echo Carbon::now()->subWeek(3)->diffForHumans();
//Result: 3 weeks ago
Enter fullscreen mode Exit fullscreen mode

PHP Carbon Format Months Ago

<?php

echo Carbon::now()->subMonth(3)->diffForHumans();
//Result: 3 months ago
Enter fullscreen mode Exit fullscreen mode

PHP Carbon Format Long Relative for Humans

<?php

echo Carbon::create('2022')->longRelativeDiffForHumans('2019');
//Result: 4 months 5 days 7 hours 31 minutes 21 seconds ago
Enter fullscreen mode Exit fullscreen mode

I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/php/php-carbon-formatting-that-readable-for-humans if you want to download this code.

Happy coding :)

Top comments (0)