Signup/Sign In

How to convert the date into the timestamp in PHP

Answer: Using strtotime() function

We can convert the date into the timestamp using the PHP strtotime() function. The timestamp is the total number of seconds calculated between the particular date and the Unix epoch.

This function takes two parameters, these are:

  • time - It is the date/time string. It is a mandatory parameter.
  • now - It specifies the timestamp used as a base for the calculation of relative dates. It is optional.

Example: Using strtotime() function

In this example, we have used the strtotime() fucntion to convert the given date into the timestamp.

<!DOCTYPE html>
<html>
<head>
  <title>Convert the date into the timestamp </title>
</head>
<body>
	<?php
		$timestamp = strtotime("27-07-2021");
		echo "The timestamp is: $timestamp.";
	?>
</body>
</html>

Output


The timestamp is: 1627336800.

Using date_timestamp_get() method

The date_timestamp_get() method is also used to convert the given date into the timestamp. This method takes the single parameter $object (date time object) which is returned by the date_create() function.

Example: Using date_timestamp_get() method

In the given example, we have used the date_timestamp_get() method to get the timestamp of the given date.

<!DOCTYPE html>
<html>
<head>
  <title>Convert the date into the timestamp </title>
</head>
<body>
	<?php
		$date = date_create();
		$timestamp = date_timestamp_get($date);
		echo "The timestamp is: $timestamp";
	?>
</body>
</html>

Output


The timestamp is: 1627383887

Using time() function

The time() function is a predefined function in PHP. This function returns the time measured in the number of seconds between the current date and Unix Epoch.

We can convert the timestamp into the current date using the date() function.

Example: Using time() function

In the given example, we have used the time() function to convert the current date into the timestamp.

<!DOCTYPE html>
<html>
<head>
  <title>Convert the date into the timestamp </title>
</head>
<body>
	<?php
		$timestamp = time();
		echo "The timestamp is: $timestamp";
	?>
</body>
</html>

Output


The timestamp is: 1627384282

Conclusion

In this lesson, we have learned how to convert the date into a timestamp. Several methods are offered by the PHP by which we can convert the current date into the timestamp. Here we have discussed the most used three methods, these are:

  • strtotime() function
  • date_timestamp_get() function
  • time() function


About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.