Date and time
PHP provides several built-in functions for working with dates and time. Internally, PHP uses Unix timestamps, which represent the number of seconds since January 1, 1970 (UTC). Most date and time operations revolve around converting between timestamps and human-readable formats.
The most important date and time functions are:
- date()
Formats a timestamp into a readable date or time string.
If no timestamp is provided, it uses the current server time. - time()
Returns the current Unix timestamp.
Useful when you need the “current moment” as a numeric value. - strtotime()
Converts a human-readable date/time string into a Unix timestamp.
This allows relative expressions like “+5 days”, “next Monday”, or “last Sunday”. - mktime()
Creates a Unix timestamp for a specific date and time by explicitly passing year, month, day, hour, minute, and second. - date_default_timezone_set()
Sets the timezone used by all date/time functions in the script. - date_default_timezone_get()
Returns the currently configured timezone.
Key concepts to understand:
- Formatting vs time calculation are separate concerns
date()is for displaying valuestime(),mktime(), andstrtotime()are for generating timestamps- Timezones must be set explicitly to avoid incorrect or inconsistent results
At this stage, the goal is to become comfortable converting between timestamps and formatted dates, not memorizing every format character.