Home  >  Article  >  Backend Development  >  Example showing how to convert PHP time to timestamp

Example showing how to convert PHP time to timestamp

PHPz
PHPzOriginal
2023-03-29 16:26:111043browse

PHP is a popular programming language used by many web developers to build powerful web applications. When dealing with time-related data, it is very common to use timestamps. A timestamp is an integer value that represents the number of seconds from the beginning of the Unix epoch to the current time. When we need to get the timestamp from the time string, we can do it through PHP's built-in function. In this article, we will show how to convert PHP time to timestamp.

  1. Using the strtotime function

There is a built-in function strtotime() in PHP that can convert a time string into a timestamp. The first parameter of the strtotime() function is a time string, and the second parameter is optional. The date and time format is specified in the first parameter. We can use the following sample code to convert a time string to a timestamp:

$timestamp = strtotime('2020-01-01 00:00:00');

echo $timestamp;

Output result:

1577836800
  1. Using the DateTime class

in PHP The DateTime class provides an object-oriented way to work with dates and times. The DateTime class can convert a time string into a DateTime object and then convert it into a timestamp using the getTimestamp() method. The following is a sample code using the DateTime class:

$date = new DateTime('2020-01-01 00:00:00');

$timestamp = $date->getTimestamp();

echo $timestamp;

Output result:

1577836800
  1. Custom function

We can also define a custom function, Convert a time string to a timestamp. Here is a sample code using a custom function:

function strToTimestamp($str) {

    $date = DateTime::createFromFormat('Y-m-d H:i:s', $str);

    return $date->getTimestamp();

}

$timestamp = strToTimestamp('2020-01-01 00:00:00');

echo $timestamp;

Output result:

1577836800

Conclusion

In PHP, there are multiple ways to convert a time string to timestamp. This functionality can be achieved whether you use built-in functions, the DateTime class, or custom functions. Which method you choose depends on personal preference and job requirements. Hope this article is helpful to you.

The above is the detailed content of Example showing how to convert PHP time to timestamp. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn