How To Manage DateTime with Carbon in Laravel and PHP

Working with date and time in PHP can be complicated. We have to deal with strtotime, formatting issues, lots of calculations, and more. The Carbon package can help make dealing with date and time in PHP much easier and more semantic so that our code can become more readable and maintainable. Carbon is a inherit methods of php datetime class.

Controller

use Illuminate\Support\Carbon; (Don't need to install directly use it)

function myfun(){ 
  $timestamps = 17897897989;
  $datetime = Carbon::createFromTimestamp($timestamps);
  echo $datetime->format('Y-m-d, H:i:s');
}
convert string into date format

function myfun(){ 
  $dateString = '2024-02-23 12:00:22';
  $datetime = Carbon::createFromFormat('Y-m-d H:i:s', $dateString);
  echo $datetime->format('Y-m-d, H:i:s');
}
string into time format

function myfun(){ 
  $dateString = '2024-02-23 12:00:22';
  $datetime = Carbon::createFromFormat('Y-m-d H:i:s', $dateString);
  echo $datetime->format('Y-m-d');
}
get current time

function myfun(){ 
  $dateString = '2024-02-23 12:00:22';
  $datetime = Carbon::createFromFormat('Y-m-d H:i:s', $dateString);
  echo $datetime->format('Y-m-d');
}
function myfun(){ 
  $dateString = '2024-02-23 12:00:22';
  $time = Carbon::now()->toTimeString();
  echo $time;
}

 

 

Leave a Reply