Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

PHP Get Current Timestamp

PHP has many native ways to get the Current Timestamp and this tutorial we will walk through each of the possibilities.

Utilizing the DateTime Class

It’s more than likely that you’ve already used the DateTime class and overlooked it’s potential. It takes one function call of a DateTime instance to get a proper timestamp.

Important note: The DateTime object, when initialized, is loaded with the Current Timestamp of execution. 

let’s take a look.

$dt = new DateTime(); // Current Time - // Sunday, 3 May 2020 16:46:31 GMT+01:00 DST
echo $dt->getTimestamp();

Output

1588521147

Using date_timestamp_get()

If you want to use a more procedural style, then PHP has this covered also. We can call the date_create() function first which does what it says on the tin. Then we can pass the variable created into another function called date_timestamp_get(), which again, does what it says on the tin. Shout out to the guy who named these functions!

Look at the following code –

$dt = date_create(); // Current Time - Sunday, 3 May 2020 16:57:47 GMT+01:00 DST
echo date_timestamp_get($dt);

Output

1588521467

Utilizing the time() function

Another very simple way to get the current timestamp is to use the time() function. This function literally executes and returns the current timestamp.

Check out the code snippet below

echo time();

Output

1588521787

This is probably by far the simplest but in a way, slightly misleading with its name.

Similarly here, we can actually use another function named microtime() which does exactly the same thing but adds on microseconds to the timestamp.

Using strtotime()

Another method is to use strtotime() passing it the ‘now’ parameter to get the current stamp. As you may know, strtotime() always parses the given context as a timestamp. So, with this in mind, the following code will be sufficient.

echo strtotime('now');

Output

1588522286

Yes, it is that simple.

Summary

It’s probably a shock to see how many different variations there actually is with PHP to get the current timestamp. When it comes down to actually using one of these methods, it will mostly down to preference. Hope this helps!

The post PHP Get Current Timestamp appeared first on Code Wall.



This post first appeared on Code Wall - Web Development & Programming, please read the originial post: here

Share the post

PHP Get Current Timestamp

×

Subscribe to Code Wall - Web Development & Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×