Master PHP’s strtotime(): Convert Human Dates to UNIX Timestamps
Learn how PHP’s strtotime() function transforms human‑readable date strings into UNIX timestamps, covering its syntax, parameters, and common formats such as relative dates, absolute dates, time intervals, and special keywords, while noting its parsing limits and extra options.
strtotime()is a powerful and flexible PHP function that converts human‑readable date and time strings into UNIX timestamps.
UNIX timestamps represent the number of seconds elapsed since 1970-01-01 00:00:00 UTC, a widely used format in computing.
Basic Syntax of strtotime()
strtotime(string $time, int $now = time()): int|falseThe $time parameter is the date/time string to be converted, and the optional $now parameter provides a base timestamp. The function returns an integer UNIX timestamp or false on failure.
Common Usage Formats of strtotime()
Relative dates and times, such as "now", "tomorrow", "next week". Example:
strtotime("tomorrow") // returns the UNIX timestamp for tomorrowAbsolute dates and times. Examples:
strtotime("2023-10-31") // timestamp for the given date
strtotime("2023-10-31 08:30:00") // timestamp for the given date and timeRelative time intervals, e.g., "+1 day", "+1 week 2 days 4 hours 30 minutes". Example:
strtotime("+1 day") // timestamp one day from now
strtotime("+1 week 2 days 4 hours 30 minutes") // timestamp after the specified intervalSpecial keywords like "last day of month" or "first day of next month". Example:
strtotime("last day of month") // timestamp for the last day of the current month
strtotime("first day of next month") // timestamp for the first day of the next monthNote that strtotime() has limited parsing capabilities; it can only handle common date formats and may fail on unusual ones, so ensure input strings follow standard formats.
Additionally, strtotime() supports extra parameters such as time zone settings or specifying weekdays, which can further enhance its flexibility.
Conclusion
The strtotime() function is a highly useful PHP tool for converting readable dates and times into UNIX timestamps, enabling easy date calculations. However, its parsing is limited, so verify that input formats conform to standards.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
