PHP | time() Function

PHP time() Function


Hello folks! welcome back to a new edition of our tutorial on PHP. In this tutorial guide, we are going to be studying about the PHP time() Function.

PHP time() function calculates the number of seconds between the Epoch (January 1 1970 00:00:00 GMT) and current time, and then returns it.

Syntax

Following below is the syntax to use this function -

time(void)


Parameter Details

This built-in PHP function does not accept any parameters.

Return Value

This built-in function returns an integer value representing the number of seconds between the Epoch and the current time.

PHP Version

This function was first introduced as part of core PHP version 4 and, it works with all the later versions.

Example1

Following example illustrates the usage of time() function -

<?php
   $time = time();
   print("Current Timestamp: ".$time);
?>

Output

When the above code is executed, it will produce the following result -

Current Timestamp: 1606146910

Example2

The following example gets the sunrise and sunset Time of the current date -

<?php
   $dateString = '11-06-2012 12:50 GMT';
   print("Date: " . date("D M d Y"));
   print("\n");
   print("Sunset time: ");
   print(date_sunset(time(),SUNFUNCS_RET_STRING,38.4,-9,90,1));
   print("\n");
   print("Sunrise time: ");
   print(date_sunrise(time(),SUNFUNCS_RET_STRING,38.4,-9,90,1));
?>

Output

When the above code is executed, it will produce the following result -

Date: Mon Nov 23 2020 
Sunset time: 18:14 
Sunrise time: 08:30

Example3

Below example adds and removes 23 days, 12 hours and, 30 minutes from the current time stamp and prints the results -

<?php
   $timestamp1 = time() - (23*12*30);
   print_r($timestamp1); 
   print("\n");
   $timestamp2 = time() + (23*12*30);
   print_r($timestamp2); 
?>

Output

When the above code is executed, it will produce the following result -

1606139150 
1606155710

Example4

Try the following example -

<?php
   $nextWeek = time() + (7 * 24 * 60 * 60);   
   echo 'Now:       '. date('Y-m-d') ."\n";
   echo 'Next Week: '. date('Y-m-d', $nextWeek) ."\n";
?>

Output

When the above code is executed, it will produce the following result -

Now: 2020-11-23 
Next Week: 2020-11-30


Alright guys! This is where we are going to be rounding up for this tutorial post. In our next tutorial, we are going to be discussing about the timezone_abbreviations_list() Function in PHP.

Do feel free to ask your questions where necessary and we will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.