Carbon library : How To Get Current Timestamp In Laravel

In Laravel, you can get the current timestamp using the now() function, which is a helper function provided by Laravel’s Carbon library. Carbon is a powerful extension for working with dates and times in PHP.

To get the current timestamp, follow these steps:

Step 1: Import the Carbon namespace
At the top of your file, import the Carbon namespace so that you can use the Carbon library:

use Carbon\Carbon;

Step 2: Get the current timestamp
You can use the now() function to get the current timestamp. Here’s an example:

$currentTimestamp = Carbon::now();

The $currentTimestamp variable will now hold the current timestamp.

Step 3: Customize the format (optional)
By default, the now() function returns a Carbon instance, which can be formatted in various ways. You can customize the format of the timestamp according to your needs. Here’s an example:

$currentTimestamp = Carbon::now()->format('Y-m-d H:i:s');

In this example, the timestamp is formatted as “YYYY-MM-DD HH:MM:SS”.

Step 4: Use the current timestamp
You can now use the $currentTimestamp variable in your code as needed. For example, you might store it in a database, use it in calculations, or display it to the user.

That’s it! You now know how to get the current timestamp in Laravel using the Carbon library.

Here’s a complete example that summarizes the steps:

use Carbon\Carbon;

$currentTimestamp = Carbon::now();
$currentTimestampFormatted = Carbon::now()->format('Y-m-d H:i:s');

// Use the current timestamp
echo "Current timestamp: " . $currentTimestamp . "\n";
echo "Formatted current timestamp: " . $currentTimestampFormatted . "\n";

This will output something like:

Current timestamp: 2023-05-19 10:30:15
Formatted current timestamp: 2023-05-19 10:30:15

In this example, the current timestamp is displayed both in its default format and in a custom format.

All the best nerd!

Leave a Reply