CodeBlanks Logo Icon CodeBlanks

Parsing dates with strtotime()

PHP course · Intermediate · Lesson 107/115

Learn to convert English date expressions to timestamps with strtotime().

The strtotime() function

In PHP you use strtotime() to convert English date expressions to a timestamp. The function takes a string like 'next Monday' or '+1 week' and returns a Unix timestamp.

For example, $ts = strtotime('2024-03-15'); turns the string '2024-03-15' into a timestamp. You can then print it in any format with date('d.m.Y', $ts).

If parsing fails the function returns false; checking the return value is a good habit.

Relative date expressions

strtotime() also understands relative expressions: '+1 day' is tomorrow, '-1 week' is last week, 'next Monday' is the next Monday, 'last day of next month' is the last day of next month.

This lets you take a phrase like 'one week later' from a user and compute it. For example, date('Y-m-d', strtotime('+1 week')) gives the date one week from today.

The parser uses English grammar; expressions must be in English, other languages are not recognised.

Exercise Parse a date string and print it

Use strtotime() to convert '2024-03-15' into a timestamp and assign it to $ts. Then print it with date('d/m/Y', $ts).

Show example solution
Write $ts = strtotime('2024-03-15'); then add echo date('d/m/Y', $ts);
Example solution:
<?php
date_default_timezone_set('UTC');

$ts = strtotime('2024-03-15');
echo date('d/m/Y', $ts);

Test yourself

  1. What does strtotime('next Monday') return?

    • A DateTime object
    • A formatted date string
    • The boolean true
    • A Unix timestamp (integer)
    Show answer

    A Unix timestamp (integer) — Correct. strtotime() returns a Unix timestamp on success.

  2. Parse one week later

    $ts = strtotime('____');
    Show answer
    $ts = strtotime('+1 week');
  3. Match relative expressions

    'yesterday'
    Yesterday's date
    'next Monday'
    Next Monday
    '+1 day'
    Tomorrow
    'last day of this month'
    Last day of this month

All lessons in Intermediate