How to Convert Timestamp into Carbon Datetime in Laravel

Unix timestamps are a way of keeping track of time. They are often used by developers to keep track of when code was last modified or to calculate how long something took to run. While they can be helpful for keeping track of time, they can also be a bit confusing.

Laravel’s Carbon library provides a convenient way to work with dates and times. In many cases, it is better to convert timestamps to utilize Carbon’s features.

You can use the createFromTimestamp() function to create a Carbon instance from a UNIX timestamp. This function will set the timezone as well or default it to the current timezone. Once you have a Carbon instance, you can use its various methods to format the timestamp in whatever way you need. For example, you could use the format() method to display the timestamp in a human-readable format.

namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Carbon\Carbon;
  
class DateController extends Controller
{

    public function index()
    {
        
        $datetime = Carbon::createFromTimestamp(-1)->toDateTimeString(); //"1970-01-01 07:29:59"
        $datetime = Carbon::createFromTimestamp(1254125678)->toDateTimeString(); //"2009-09-28 16:14:38"
        $datetime = Carbon::createFromTimestamp(1654009995)->toDateTimeString(); //""2022-05-31 23:13:15"

        $datetime = Carbon::createFromTimestampUTC('1654010143')->format('Y-m-d\TH:i:s.uP'); //"2022-05-31T15:15:43.000000+00:00"
        $datetime = Carbon::createFromTimestampUTC('954075600')->format('Y-m-d'); //"2000-03-26"

    }
}

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close