Table of Contents
Get Current Timestamp
Convert Timestamp to Readable Date
Convert Date to Timestamp
Use DateTime for More Control
Home Backend Development PHP Tutorial How to work with timestamps in PHP?

How to work with timestamps in PHP?

Aug 31, 2025 am 08:55 AM
php Timestamp

Use time() to get the current timestamp, date() formats the time, and strtotime() converts the date string to a timestamp. It is recommended that the DateTime class handles time zone and date operations for complex operations.

How to work with timestamps in PHP?

Working with timestamps in PHP is straightforward thanks to built-in functions and the DateTime class. Timestamps are typically represented as Unix timestamps — the number of seconds since January 1, 1970 (UTC). Here's how to handle common tasks effectively.

Get Current Timestamp

To get the current Unix timestamp, use the time() function.

$now = time();
echo $now; // Outputs something like: 1715000000

This gives you an integer you can store or compare.

Convert Timestamp to Readable Date

Use date() to format a timestamp into a human-readable string.

$timestamp = time();
$formatted = date('Ymd H:i:s', $timestamp);
echo $formatted; // Outputs: 2024-05-06 14:30:22

The first argument defines the format. Common format characters include:

  • Y – 4-digit year
  • m – Month with leading zero
  • d – Day with leading zero
  • H – 24-hour format hour
  • i – Minutes with leading zero
  • s – Seconds with leading zero

Convert Date to Timestamp

If you have a date string, use strtotime() to convert it to a Unix timestamp.

$dateString = "2024-05-06 14:30:00";
$timestamp = strtotime($dateString);
echo $timestamp; // Outputs: 1715000000

This function parses many formats, including relative strings like "next Monday" or " 1 week".

Use DateTime for More Control

For complex operations, the DateTime class is more powerful and timezone-aware.

$datetime = new DateTime('2024-05-06 14:30:00', new DateTimeZone('UTC'));
echo $datetime->getTimestamp(); // Get Unix timestamp
echo $datetime->format('Ymd H:i:s'); // Format output

You can also modify dates:

$datetime->modify(' 1 day');
$datetime->add(new DateInterval('P1Y2M')); // Add 1 year and 2 months

DateTime handles timezones properly, which is cruel when working with users in different regions.

Basically, use time() and date() for simple cases, and switch to DateTime when you need timezone support, date math, or parsing varied formats. It's not complex, but easy to get wrong without attention to timezone context.

The above is the detailed content of How to work with timestamps in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to prevent XSS (Cross-Site Scripting) attacks in PHP? How to prevent XSS (Cross-Site Scripting) attacks in PHP? Sep 15, 2025 am 12:10 AM

PreventXSSbyescapingoutputwithhtmlspecialchars()orjson_encode(),validatinginputusingfilter_var(),applyingCSPheaders,andusingsecureframeworkslikeLaravel.

How to get POST data in PHP? How to get POST data in PHP? Sep 16, 2025 am 01:47 AM

Use the $_POST hyperglobal array to obtain POST data, read the value through the form name attribute, and use a foreach loop when processing array input, so that the data needs to be verified and filtered to prevent XSS.

How to add a watermark to an image in php How to add a watermark to an image in php Sep 15, 2025 am 03:26 AM

Use PHP's GD library to add watermarks to images. First load the original image and watermark (text or image), then use imagecopy() or imagettftext() to merge, and finally save the output. Support JPEG, PNG and other formats, pay attention to handling transparency and font paths, and ensure that GD extension is enabled.

Aisi Assistant's genuine download portal_Aisi Assistant's iPhone installation link Aisi Assistant's genuine download portal_Aisi Assistant's iPhone installation link Sep 16, 2025 am 11:30 AM

The official download portal of Aisi Assistant is located on the official website https://www.i4.cn/, and provides computer and mobile downloads, supporting device management, application installation, mode switching, screen projection and file management functions.

How to convert an object to an array in PHP? How to convert an object to an array in PHP? Sep 14, 2025 am 03:14 AM

Use (array) to convert simple objects into arrays. If they contain private or protected properties, the key names will have special characters; for nested objects, recursive functions should be used to traverse the conversion to ensure that all hierarchical objects become associative arrays.

How to work with environment variables in PHP? How to work with environment variables in PHP? Sep 15, 2025 am 03:55 AM

Usegetenv()toreadenvironmentvariablesandvlucas/phpdotenvtoload.envfilesindevelopment;storesensitivedatalikeAPIkeysoutsidecode,nevercommit.envtoversioncontrol,anduseactualenvironmentvariablesinproductionforsecurity.

How to make an API call using cURL in PHP? How to make an API call using cURL in PHP? Sep 15, 2025 am 05:16 AM

InitializecURLwithcurl_init(),setoptionslikeURL,method,andheaders,senddatausingPOSTorcustommethods,handleresponseviacurl_exec(),checkerrorswithcurl_error(),retrievestatususingcurl_getinfo(),decodeJSONresponse,andclosewithcurl_close().

How to get the request method (GET, POST, PUT) in PHP? How to get the request method (GET, POST, PUT) in PHP? Sep 16, 2025 am 04:17 AM

Use $_SERVER['REQUEST_METHOD'] to obtain HTTP request methods, such as GET, POST, PUT, DELETE; for PUT and other methods, you need to read the original data through file_get_contents('php://input'), and use the switch statement to process different request types.

See all articles