How to work with timestamps in PHP?
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.
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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.

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.

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.

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.

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

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

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.
